tags:

views:

964

answers:

2

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?

+3  A: 

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.Where( c => c.Id == id )
                                  .SingleOrDefault();

     UpdateModel(contact, new string[] { "Email" } );
     string[] whitelist = new string[] { "Forename", "Surname" };
     UpdateModel( contact.Name, "Name", whitelist );
 }
tvanfosson
This works great, Thanks tvanfosson.
+3  A: 

Thats very interesting because if you had done

public ActionResult Save( int id, Contact contact )
{
    //contact here would contain the nested values.
}

I'm using this with great success. I suppose then you could somehow sync the two Contact objects together.

I would have thought that the UpdateModel and the binding to the parameter use the same call behind the scenes. note: haven't tried to reproduce your issue.

Schotime