Posting to a list MVC3

后端 未结 1 1147
谎友^
谎友^ 2020-11-28 11:01

I am trying to get my view to post a List back to the action however it keeps coming in as null.

So my Model has a List of WeightEntry objects.

Exercise Mode

相关标签:
1条回答
  • 2020-11-28 11:20

    Replace the following loop:

    @foreach (var item in Model.Entries)
    {
        <tr>
            <td>
                @Html.EditorFor(x => item.Repetition)
             </td>
             <td>
                 @Html.EditorFor(x => item.Weight)
             </td>
         </tr>
    }
    

    with:

    @for (var i = 0; i < Model.Entries.Count; i++)
    {
        <tr>
            <td>
                @Html.EditorFor(x => x.Entries[i].Repetition)
             </td>
             <td>
                 @Html.EditorFor(x => x.Entries[i].Weight)
             </td>
         </tr>
    }
    

    or even better, use editor templates and replace the loop with:

    @Html.EditorFor(x => x.Entries)
    

    and then define a custom editor template that will automatically be rendered for each element of the Entries collection (~/Views/Shared/EditorTemplates/WeightEntry.cshtml):

    @model WeightEntry
    <tr>
        <td>
            @Html.EditorFor(x => x.Repetition)
         </td>
         <td>
             @Html.EditorFor(x => x.Weight)
         </td>
     </tr>
    

    The the generated input elements will have correct names and you will be able to successfully fetch them back in your POST action.

    0 讨论(0)
提交回复
热议问题