问题
I have two models:
public class PersonViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Title { get; set; }
}
public class DetailViewModel
{
public IEnumerable<string> Titles { get; set; }
public PersonViewModel Person { get; set; }
}
The form is presented with two fields, the first field being the Name
, the second field being the a dropdown of Titles
(Mr., Mrs. Miss., etc.)
The view for this page is strongly typed to DetailViewModel
, and the Save
method in the controller accepts a parameter of type PersonViewModel
.
Since the view is strongly typed to a type that is different from the form action's parameter type, the names in the HttpRequest do not match what MVC is expecting in the action.
Is it possible to have MVC bind correctly with the model mismatch without having to manually specify form field names? (eg. I still want to use @Html.TextBoxFor(m => m.Person.Name)
)
For clarification, the form field names that are being submitted are similar to the following:
Person.Name=Matthew&Person.Title=Mr.
Where I need the following (for model binding to work):
Name=Matthew&Title=Mr.
回答1:
You can use the Prefix
property of BindAttribute
in the action method
public ActionResult Edit([Bind(Prefix="Person")]PersonViewModel model)
{
}
This essentially strips the Person
prefix from the property name while binding
来源:https://stackoverflow.com/questions/27070547/submitting-a-model-to-action-that-is-different-from-view-models-type