如何编辑MVC4表单中的子对象?

Rob*_*ous 5 asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我有以下内容:

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

如何编辑子对象?我也试过这样的事情:

<input type="hidden" name="children.Index" value="@child.Id" />
<textarea name="children[@child.Id]" >@child.Name</textarea>
Run Code Online (Sandbox Code Playgroud)

要将IDictionary传递给控制器​​,但我收到错误:

[InvalidCastException: Specified cast is not valid.]
   System.Web.Mvc.CollectionHelpers.ReplaceDictionaryImpl(IDictionary`2 dictionary, IEnumerable`1 newContents) +131
Run Code Online (Sandbox Code Playgroud)

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

Dar*_*rov 11

有一个简单的解决方案吗?

是.

我错过了什么?

编辑模板.

我需要使用编辑模板吗?

是.

如果是这样,任何兼容MVC4的例子都会很棒.

ASP.NET MVC 4?自从ASP.NET MVC 2以来,存在编辑器模板.您需要做的就是使用它们.

所以首先摆脱外部foreach循环并将其替换为:

@model MyViewModel
@Html.EditorFor(x => x.Parents)
Run Code Online (Sandbox Code Playgroud)

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

@model Parent
@Html.EditorFor(x => x.Children)
Run Code Online (Sandbox Code Playgroud)

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

@model Child
@Html.TextAreaFor(x => x.name)
Run Code Online (Sandbox Code Playgroud)

一切都按照ASP.NET MVC中的约定进行.所以在这个例子中我假设它Parents是一个IEnumerable<Parent>并且Children是一个IEnumerable<Child>.相应地调整模板的名称.

结论:每次使用foreachfor在ASP.NET MVC视图中,您都做错了,您应该考虑将其删除并用编辑器/显示模板替换它.