当前位置: 动力学知识库 > 问答 > 编程问答 >

Model binding of nested properties in 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?

网友答案:

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 );
 }
网友答案:

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.

网友答案:

To bind a Name rather than the whole view model on POST is to instruct the model binder that a prefix will be used. This is done using the BindAttribute.

public ActionResult AddComment([Bind(Prefix = "Name")] Name name)
{
  //do something
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: