Asp.Net MVC3 Razor - child items list not posting back from editor

一曲冷凌霜 提交于 2019-12-05 14:16:36

Your templates are not named correctly. Should be:

  • ~/Views/Shared/EditorTemplates/Child.cshtml
  • ~/Views/Shared/EditorTemplates/SubChild.cshtml

Also I don't quite see the purpose of the SubChildren property on your view model.

You could remove it and in your main view:

@model MvcApplication1.Models.ViewModels.ParentViewModel

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>

    @Html.HiddenFor(model => model.Id)
    @Html.LabelFor(model => model.Name)
    @Html.EditorFor(model => model.Name)
    <hr />
    Child
    <br />
    @Html.EditorFor(model => model.Child)

    <hr />
    SubChild
    <br />
    @Html.EditorFor(model => model.Child.SubChildren)

    <p>
        <input type="submit" value="Save" />
    </p>
    </fieldset>
}

But your biggest problem is that you have nested HTML <form> elements which is not allowed. It's invalid HTML and results into undefined behavior. Some values might be posted, others not, ... Remove all Html.BeginForm helpers from inside your templates because your main view already contains a form.

See this article for a solution. The magic is contained in the using(Html.BeginCollectionItem("...")) block.

In short, you have to use the correct field names / prefixes when working with the default modelbinder.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!