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

前端 未结 2 1813
予麋鹿
予麋鹿 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);
    
        <input type="submit" value="Submit" />
    }
    
    • 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
    
    <p>
        @Html.DisplayFor(m => m.Text)
        @Html.CheckBoxFor(m => m.IsSelected)
        @Html.HiddenFor(m => m.Id)
        @Html.HiddenFor(m => m.Text)
    </p>
    

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

    0 讨论(0)
  • 2020-12-07 20:02

    I found this thread while looking for something else related. Denis has the correct answer, but I thought I would add some syntax in case anyone else comes across this:

    If you have an editor template named "SomeTemplate.cshtml" you can use it for a list of Item as follows in your view:

    @for (var i = 0; i < Model.ObjectList.Count(); i++)
    {
        @Html.EditorFor(m => m.ObjectList[i], "SomeTemplate")
    }
    

    Then in your editor template:

    @model WebTestApplication.Models.ContainedObject
    
    <br />
    @Html.Label(Model.Text);
    @Html.CheckBoxFor(m => m.IsSelected);
    @Html.HiddenFor(m => m.Id);
    @Html.HiddenFor(m => m.Text);
    
    0 讨论(0)
提交回复
热议问题