【问题标题】:MVC5 model binding -- child objects all nullMVC5 模型绑定——子对象全部为空
【发布时间】:2015-04-23 00:02:56
【问题描述】:

当我的父类/模型回传到服务器并且我使用 BindAttribute“绑定”时,子对象都是空的。

如果我不包含绑定,那么它可以工作
public ActionResult SaveEdit(int id, Person person)

例如 person.Address 属性不为空,它的属性是根据表单提交设置的。

仅供参考,地址是使用 EditorFor 在视图中创建的,所有内容都包含在请求表单中。

但如果我使用 Bind,它就不起作用..

public ActionResult SaveEdit(int id, [Bind(Include = "PersonId, AddressId, Address.AddressId, Address.Line1, Address.City, Address.State, Address.Zip")] Person person)

person.PersonId 和 person.AddressId 设置正确,但是 person.Address 为空。

如果使用Bind和多个参数,像这样...

    public ActionResult SaveEdit(int id, [Bind(Include = "PersonId")] Person person, 
       [Bind(Prefix = "Address", Include = "AddressId, Line1, City, State, Zip")] Address address)

它成功了,两个对象都被创建了,通常都没有相关的属性。

这是正常行为,还是我做错了什么?

【问题讨论】:

  • [Bind(Include = "PersonId, AddressId, Address")] 应该可以工作,但如果您需要使用[Bind(Include ="..")],请停止并使用仅包含您需要编辑的属性的视图模型。
  • @StephenMuecke:将其发布为答案,我会接受...

标签: c# asp.net-mvc-5 model-binding


【解决方案1】:

您尚未展示您的模型,但假设它包含属性PersonIdAddressIdAddress 其中Address 是一个复杂对象,那么它必须是

public ActionResult SaveEdit(int id, [Bind(Include = "PersonId, AddressId, Address")] Person person)

但是,更好的方法是使用仅包含您正在编辑的属性的视图模型,并避免使用[Bind(Include = "properties, list")]

【讨论】:

  • 只是为了确定,“..”是缩写吗?还是另一种语法?
  • 是的,它只是一个占位符 - 我懒得添加所有文本 :)
猜你喜欢
  • 2011-05-22
  • 1970-01-01
  • 1970-01-01
  • 2014-11-06
  • 2017-03-06
  • 2011-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多