ASP.NET MVC subproperty's deserialization
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 开发者_JAVA技巧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 Controller
is a reserved keyword and the default model binder doesn't like it. Try renaming the property:
public class TaskViewModel
{
public UserViewModel TaskController { get; set; }
public UserViewModel AssignedTo { get; set; }
}
The whole problem comes from the ValueProvider that the default model binder uses. When it encounters the Controller
navigation property it does this:
var value = ValueProvider.GetValue("Controller");
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 UserViewModel
cannot result in success.
精彩评论