嵌套属性的模型绑定在asp.net mvc中

12 asp.net-mvc

我想在我的mvc应用程序中使用一些绑定工具.我发现嵌套属性不会被asp.net mvc的RC1版本中的默认模型绑定器自动绑定.我有以下类结构:

public class Contact{  
    public int Id { get; set; }  
    public Name Name { get; set; }  
    public string Email { get; set; }  
}
Run Code Online (Sandbox Code Playgroud)

在哪里Name定义为:

public class Name{  
    public string Forename { get; set; }  
    public string Surname { get; set; }  
}
Run Code Online (Sandbox Code Playgroud)

我的观点定义如下:

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");  
}
Run Code Online (Sandbox Code Playgroud)

我的控制器动作定义为:

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!!!
}
Run Code Online (Sandbox Code Playgroud)

Email属性已成功绑定,但不是Name.ForenameName.Surname属性.任何人都可以告诉我这是否应该使用默认的模型绑定器,我做错了什么或者如果它不起作用,我需要滚动我自己的代码来绑定模型对象上的嵌套属性?

tva*_*son 9

我认为问题是由于属性上的Name前缀.我认为您需要将其更新为两个模型并指定第二个模型的前缀.请注意,我已从FormCollection参数中删除了该参数并使用了UpdateModel依赖于内置值提供程序的签名,并指定了要考虑的属性白名单.

 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 );
 }
Run Code Online (Sandbox Code Playgroud)


Mat*_*cic 5

在POST上绑定Name而不是整个视图模型是指示模型绑定器将使用前缀.这是使用BindAttribute完成的.

public ActionResult AddComment([Bind(Prefix = "Name")] Name name)
{
  //do something
}
Run Code Online (Sandbox Code Playgroud)