Reputation: 35587
My model contains two objects (Reminders and Users). Each reminder is associated with one user.
public class Reminder
{
[DisplayName("Subject")]
[Required(ErrorMessage = "{0}: error message.")]
[StringLength(200, ErrorMessage = "{0}: error message.")]
public string Name { get; set; }
[DisplayName("Supervisor")]
public User DepartmentSupervisor { get; set; }
}
public class User
{
[DisplayName("Username")]
[Required(ErrorMessage = "{0}: error message.")]
[StringLength(25, ErrorMessage = "{0}: lerror message.")]
public string Username { get; set; }
[DisplayName("Email")]
[StringLength(50, ErrorMessage = "{0}: error message.")]
[Email(ErrorMessage="Not valid.")]
public string Email { get; set; }
}
I've defined a viewmodel I use to pass data to my view:
public class RemindersViewModel
{
public RemindersViewModel()
{
this.Supervisors = new List<SelectListItem>();
}
public Models.Reminder Reminder { get; set; }
public List<SelectListItem> Supervisors { get; set; }
}
Supervisors is a list of Users (SelectListItem) I use to render a combo.
When I submit the form the controller rebinds the object Reminder:
public ActionResult Edit(Guid id, Models.Reminder Reminder)
{
if (!ModelState.IsValid)
{
// PROBLEM.
}
}
Everything works fine and I have my reminder associated with the choosen user (username) but, since I don't need to show the email in the dropdown, the binding can't fill the field, cause it doesn't exists in my form. In the validation process I get an error cause it tries to validate the User model, which is not what I really want. What's the best approach dealing with nested models?
Upvotes: 1
Views: 796
Reputation: 1038710
Have you considered using view models? They include only the properties your view requires and the validation for this particular view. So if your view doesn't require an email you write a view model without an email and the validation passes great. Then inside your controller action you map this view model to the corresponding domain model. AutoMapper is a great tool for this job.
Upvotes: 1