I have two identical dropdownlists for identical subproperties of my item TaskViewModel.
@Html.DropDownListFor(x => x.AssignedTo.ID, TaskHelper.GetUsersSelect(Model.AssignedTo), new { @class = "select" })
@Html.DropDownListFor(x => x.Controller.ID, TaskHelper.GetUsersSelect(Model.Controller), new { @class = "select" })
Both values sending on posting form (…&AssignedTo.ID=1&Controller.ID=1…), but I always get only task.AssignedTo deserialized
public ActionResult SaveTask(TaskViewModel task)
{
task.AssignedTo.ID //value here
task.Controller.ID //null reference exception
}
public class TaskViewModel
{
public UserViewModel Controller { get; set; }
public UserViewModel AssignedTo{ get; set; }
}
public class UserViewModel
{
public long ID { get; set; }
public string Title { get; set; }
}
What may be a reason for that strange behaviour?
It looks like
Controlleris a reserved keyword and the default model binder doesn’t like it. Try renaming the property:The whole problem comes from the ValueProvider that the default model binder uses. When it encounters the
Controllernavigation property it does this:which unfortunately first looks at route data and after that in query string. So this returns “Home” or whatever the name of the controller is and obviously trying to assign the string “Home” to a class of type
UserViewModelcannot result in success.