Submitting a model to action that is different from view model's type

我只是一个虾纸丫 提交于 2019-12-24 10:39:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!