【问题标题】:MVC3 Edit object containing collectionMVC3 编辑包含集合的对象
【发布时间】:2011-04-17 19:15:25
【问题描述】:

我正在尝试为以下模型工作编辑表单和控制器操作:

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

我为 Form 模型创建了 Edit 视图,为 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

“创建”操作的工作方式与魅力几乎相同 - 我能够创建新对象,并将其他对象集合作为其属性。所以我不确定为什么 Edit 不能以同样的方式工作......有什么想法吗?

更新

在多次尝试实现目标后 - 更新了 FormElement 的 IEnumerable,我发现这篇文章 http://www.codetuning.net/blog/post/Binding-Model-Graphs-with-ASPNETMVC.aspx 描述了正在发生的事情以及如何解决它。

【问题讨论】:

    标签: c# entity-framework asp.net-mvc-3 razor


    【解决方案1】:

    试试

    TryUpdateModel(form, collection);
    

    编辑:

    另见this post.

    【讨论】:

    • 这几乎奏效了 :) 它越过了 TryUpdateModel 行,但停在 db.SaveChanges();投掷:The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted. 我在这里缺少什么 - 只是编辑表单,没有修改任何关系
    • 是的,这很奇怪。我看到尝试执行删除操作的人的操作失败,他们有点有解决方案,但似乎没有其他人对编辑/更新操作有问题。
    • 我尝试使用相同的编辑器模板为 IEnumerable 创建编辑视图,但在这种情况下,应用程序不会抛出任何异常,尽管对集合所做的任何更改都不会保留在数据库中:(
    • 与此同时,我已经确认编辑器模板已实现所有属性,并且发布到 HttpPost Edit 方法的 FormCollection 正确(名称 + 值)所以我很困惑
    猜你喜欢
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 2012-05-21
    • 1970-01-01
    • 2014-03-20
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    相关资源
    最近更新 更多