Asp:net MVC 3: @Html.EditorFor a subcollection of my model in a template?

前端 未结 2 1814
予麋鹿
予麋鹿 2020-12-07 19:16

I\'ve been stuck a long time to edit a subcollection of my model, the collection of the model was coming null.

I finally found a solution, but I find it a little dir

2条回答
  •  眼角桃花
    2020-12-07 19:51

    You can simplify your code by introducing the EditorTemplate. Here is how:

    • The main view remains pretty much the same except we replaced RenderPartial with EditorFor:

    TestForm.cshtml

    @model WebTestApplication.Models.ContainerObject
    
    @{
        ViewBag.Title = "TestForm";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    @using (Html.BeginForm("TestFormResult", "Home", FormMethod.Post)) {
        @Html.EditorFor(m => m.Title)
        @Html.EditorFor(m => m.ObjectList);
    
        
    }
    
    • Then create a folder named EditorTemplates under Views/Home (assuming your controller is Home):

    enter image description here

    • and add the following template for the ContainedObject:

    ContainedObject.cshtml

    @model WebTestApplication.Models.ContainedObject
    
    

    @Html.DisplayFor(m => m.Text) @Html.CheckBoxFor(m => m.IsSelected) @Html.HiddenFor(m => m.Id) @Html.HiddenFor(m => m.Text)

    The editor will automatically iterate through the list of objects rendering the view for each of them. Hope it helps.

提交回复
热议问题