asp.net-mvc - 如何在 MVC4 表单中编辑子对象?

标签 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)    
    }                   
}

我怎样才能让编辑对子对象起作用?我也尝试过这样的事情:
<input type="hidden" name="children.Index" value="@child.Id" />
<textarea name="children[@child.Id]" >@child.Name</textarea>

将 IDictionary 传递给 Controller ​​,但出现错误:
[InvalidCastException: Specified cast is not valid.]
   System.Web.Mvc.CollectionHelpers.ReplaceDictionaryImpl(IDictionary`2 dictionary, IEnumerable`1 newContents) +131

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

最佳答案

is there a simple solution to this?



是的。

What am I missing?



编辑器模板。

Do I need to use an Editor Template?



是的。

If so, any MVC4-compatible examples would be fantastic.



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 中,一切都按照约定进行。所以在这个例子中,我假设 ParentsIEnumerable<Parent>ChildrenIEnumerable<Child> .相应地调整模板的名称。

结论:每次使用 foreachfor在 ASP.NET MVC View 中,您做错了,您应该考虑摆脱它并用编辑器/显示模板替换它。

关于asp.net-mvc - 如何在 MVC4 表单中编辑子对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15234912/

相关文章:

c# - Context.User 在 Asp.net MVC 应用程序中通过 windows auth 在 Application_AuthenticateRequest 中为 NULL

asp.net-mvc-3 - 使用.SetValidator()时,FluentValidation.Net不会产生客户端非侵入式验证

asp.net-mvc - Asp.Net - MVC - System.Collections.Generic.IEnumerable

javascript - 如何将 Facebook 评论添加到单页应用程序?

c# - 如何根据 MVC 中的下拉选择填充文本框?

c# - 返回匿名类型的简单方法(使使用 LINQ 的 MVC 成为可能)

asp.net-mvc - ASP.NET MVC筛选产生列表/网格

jquery - jQuery DataTables 如何应用于 MVC4 中的 AJAX 渲染部分 View ?

html - 事件类不能在 Bootstrap 导航栏上与 li 一起使用

asp.net-mvc-3 - Razor 生成单行文本