Asp.net-mvc – Model binding of nested properties in asp.net mvc

asp.net-mvc

I'm wanting to get some binding working in my mvc application. I find nested properties are not automatically bound by the default model binder in the RC1 release of asp.net mvc. I have the following class structure:

public class Contact{  
    public int Id { get; set; }  
    public Name Name { get; set; }  
    public string Email { get; set; }  
}

Where Name is defined as:

public class Name{  
    public string Forename { get; set; }  
    public string Surname { get; set; }  
}

My view is defined along the lines of:

using(Html.BeginForm()){  
    Html.Textbox("Name.Forename", Model.Name.Forename);  
    Html.Textbox("Name.Surname", Model.Name.Surname);  
    Html.Textbox("Email", Model.Email);  
    Html.SubmitButton("save", "Save");  
}

My controller action is defined as:

public ActionResult Save(int id, FormCollection submittedValues){  
    Contact contact = get contact from database;  
    UpdateModel(contact, submittedValues.ToValueProvider());  

    //at this point the Name property has not been successfully populated using the default model binder!!!
}

The Email property is successfully bound but not the Name.Forename or Name.Surname properties. Can anyone tell if this should work using the default model binder and I'm doing something wrong or if it doesn't work and I need to roll my own code for binding nested properties on model objects?

Best Answer

I think the problem is due to the Name prefix on the properties. I think you'll need to update it as two models and specify the prefix for the second one. Note that I've removed the FormCollection from the parameters and used the signature of UpdateModel that relies on the built-in value provider and specifies a whitelist of properties to consider.

 public ActionResult Save( int id )
 {
     Contact contact = db.Contacts.SingleOrDefault(c => c.Id == id);

     UpdateModel(contact, new string[] { "Email" } );
     string[] whitelist = new string[] { "Forename", "Surname" };
     UpdateModel( contact.Name, "Name", whitelist );
 }