加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 03:38:08 所属栏目:asp.Net 来源:网络整理
导读:我有以下内容: @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" /textar
我有以下内容:

@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的例子都会很棒.

解决方法

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>和儿童是IEnumerable< Child>.相应地调整模板的名称.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读