我有以下几点:
@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 中,一切都按照约定进行。所以在这个例子中,我假设
Parents
是 IEnumerable<Parent>
和 Children
是 IEnumerable<Child>
.相应地调整模板的名称。结论:每次使用
foreach
或 for
在 ASP.NET MVC View 中,您做错了,您应该考虑摆脱它并用编辑器/显示模板替换它。
关于asp.net-mvc - 如何在 MVC4 表单中编辑子对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15234912/