编辑包含集合的对象

本文关键字:对象 集合 包含 编辑 | 更新日期: 2023-09-27 17:50:20

我正试图使编辑表单和控制器动作为以下模型工作:

public class Form {
    public int ID {get;set;}
    public List<FormElement> formElements {get;set;}
}
public class FormElement {
    public int ID {get;set;}
    public int FormID {get;set;}
    public string Question {get;set;}
    public string Answer {get;set;}
}

我已经为表单模型创建了编辑视图,为FormElement使用了EditorTemplate。看起来不错,表单元素呈现正常但当我提交表单时,得到:

The model of type 'testApp.Models.Form' could not be updated.
Line 35:         {
Line 36:             var form = db.Forms.Single(f => f.ID== id);
Line 37:             UpdateModel(form, collection); // <- highlighted

Create动作就像一个魅力一样完成了几乎相同的方式-我能够创建新的对象与其他对象的集合作为它的属性。所以我不确定为什么Edit不能以同样的方式工作……有什么想法吗?

<标题> 更新

经过几次尝试实现目标-有我的IEnumerable的FormElement更新后,我发现这篇文章http://www.codetuning.net/blog/post/Binding-Model-Graphs-with-ASPNETMVC.aspx是描述发生了什么,以及如何解决它

编辑包含集合的对象

Try

TryUpdateModel(form, collection);
编辑: