我该如何在MVC4表单中编辑子对象?

5

我有以下内容:

@foreach (var parent in Model.Parents)
{      
    @foreach (var child in parent.Children)
    {    
        @Html.TextAreaFor(c => child.name)    
    }                   
}

如何使子对象的编辑功能正常工作?我也尝试了像这样的方法:
<input type="hidden" name="children.Index" value="@child.Id" />
<textarea name="children[@child.Id]" >@child.Name</textarea>

将IDictionary传递给控制器,但我遇到了错误:
[InvalidCastException: Specified cast is not valid.]
   System.Web.Mvc.CollectionHelpers.ReplaceDictionaryImpl(IDictionary`2 dictionary, IEnumerable`1 newContents) +131

这似乎是一项非常常见的任务...有没有简单的解决方案?我错过了什么吗?需要使用编辑器模板吗?如果需要,那么任何MVC4兼容的示例都会很棒。

1个回答

11

有没有简单的解决方案?

有。

我错过了什么?

编辑器模板。

我需要使用编辑器模板吗?

是的。

如果需要,是否有任何MVC4兼容的示例?

ASP.NET MVC 4?使用自 ASP.NET MVC 2 开始就已经存在编辑器模板了。你只需要使用它们。

因此,首先摆脱外部的 foreach 循环,然后用以下内容替换:

@model MyViewModel
@Html.EditorFor(x => x.Parents)

然后显然需要定义一个编辑器模板,该模板将自动呈现Parents集合的每个元素(~/Views/Shared/EditorTemplates/Parent.cshtml):

@model Parent
@Html.EditorFor(x => x.Children)

然后为Children集合的每个元素准备一个编辑器模板(~/Views/Shared/Editortemplates/Child.cshtml),在这里我们将摆脱内部的foreach元素:

@model Child
@Html.TextAreaFor(x => x.name)

在ASP.NET MVC中,一切都遵循惯例。因此,在这个例子中,我假设Parents是一个IEnumerable<Parent>,而Children是一个IEnumerable<Child>。请相应地调整您的模板名称。
结论:每当您在ASP.NET MVC视图中使用foreachfor时,都是错误的,您应该考虑摆脱它,并用编辑器/显示模板替换它。

谢谢Darin。我现在正在使用模板,它们非常棒。干杯! - RobVious

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接