问题
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