views:

57

answers:

1

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  A: 

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;
}
Luke
I am not using MVC 2, so does this mean that I have to create input elements for all my fields? What's the deal with [Bind(Prefix = ... ?
H. Abraham Chavez
I'm not familiar with Bind(Prefix...How are you currently creating the form elements that are posted?
Luke