Two fields with the same name

烈酒焚心 提交于 2019-12-24 01:36:09

问题


I have a ViewModel class to encapsulate "Personal" and "Business" models. My problem is that both models have a property called "Email" and the model binding is not able to make a distinction between the two.

I read that [Bind(Prefix = ... is used to resolved this issue, but I have not been able to see a concise example on how to achieve this.

public class BusinessFormViewModel
{
    public Business Business { get; set; }
    public ContactPerson ContactPerson { get; set; }

    public BusinessFromView(Business business, ContactPerson contactPerson)
    {
        Business = business;
        ContactPerson = contactPerson;
    }
}

How do I use the Bind Prefix to fix this?


回答1:


I believe that if the form elements that are posted have prefixes included in the name, the binding will be done properly. This is how the templated helpers (i.e. EditorFor) renders the controls, and my nested viewmodels are bound properly. For example, in your case, your view would have form elements something like this:

...
<input type="text" name="Business.Email" value="<%=this.Model.Business.Email %>" />
...
<input type="text" name="ContactPerson.Email" value="<%=this.Model.ContactPerson.Email %>" />
...

Or, using templated helpers (in mvc 2):

...
<%= Html.TextBoxFor(m => m.Business.Email) %>
...
<%= Html.TextBoxFor(m => m.ContactPerson.Email) %>
...

And your controller would simply take a BusinessFormViewModel as a parameter, as so:

public BusinessFromView(BusinessFormViewModel businessForm)
{
    Business = businessForm.Business;
    ContactPerson = businessForm.ContactPerson;
}


来源:https://stackoverflow.com/questions/2654273/two-fields-with-the-same-name

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