MVC3 Razor httppost return complex objects child collections

笑着哭i 提交于 2019-12-06 15:12:19

You should not iterate over children manually, you should define editor template for myOtherClass and then just let framework generate editors for all items collection.

Create EditorTemplate for myOtherClass at ~/Views/Shared/EditorTemplates/myOtherClass.cshtml

@model myOterClass
@Html.EditorFor(model => model.Name)
@Html.EditorFor(model => model.Age)

Then in parent view

@Html.EditorFor(model => model.Children)

This will internally call your editor template for all items in collection, and generate correct input names for model binding.

in View:

@for (int i = 0; i < Model.Children.Count; i++)
{
  <div class="editor-field">
    @Html.EditorFor(m => m.Children[i].Name)
  </div>

}

and in controller:

public ActionResult Test()
{
    var model = new myClass();
    model.Name = "name";
    model.Location= "loc";

    model.Children = new List<myOtherClass>();
    var child1 = new myOtherClass();
    child1.Name = "Name1";

    var child2 = new myOtherClass();
    child2.Name = "Name2";

    model.Children.Add(child1);
    model.Children.Add(child2);
    return View(model);
}

[HttpPost]
public ActionResult Test(myClass model)
{
    //model.Children Has Value
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!