Posting to a list MVC3

后端 未结 1 1148
谎友^
谎友^ 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)
    {
        
            
                @Html.EditorFor(x => item.Repetition)
             
             
                 @Html.EditorFor(x => item.Weight)
             
         
    }
    

    with:

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

    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
    
        
            @Html.EditorFor(x => x.Repetition)
         
         
             @Html.EditorFor(x => x.Weight)
         
     
    

    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)
提交回复
热议问题