在asp.net mvc的嵌套属性的模型绑定 [英] Model binding of nested properties in asp.net mvc

查看:142
本文介绍了在asp.net mvc的嵌套属性的模型绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望得到一些具有约束力的工作在我的MVC应用程序。我觉得嵌套属性不会自动在asp.net MVC的RC1版本的默认模式粘结剂粘结。我有以下类的结构:

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; }  
}

其中,名称的定义是:

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!!!
}

电子邮件属性绑定成功,而不是 Name.Forename 名称。姓属性。谁能告诉我们,如果这应该使用默认的模型绑定,我做错了什么,或者如果它不工作,我需要推出自己的code对模型对象绑定嵌套的属性?

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?

推荐答案

我认为这个问题是由于对属性名称preFIX。我认为你需要更新它的两款车型,并指定为第二个的preFIX。请注意,我已经删除了的FormCollection 从参数和使用的UpdateModel 的依赖于签名内置价值提供者和指定属性的白名单来考虑。

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 );
 }

这篇关于在asp.net mvc的嵌套属性的模型绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆