Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModelBinding on model collection

I am trying to create a very simple form to post back some values from a collection of models

When i click submit, and look at the collection returned it does not contain any objects. I also se that the asp-for does not generate the collection index that i expected.

I have a simple model

public class CustomModel
{
    public int Id { get; set; }
    public string Question { get; set; }
    public string Answer { get; set; }
}

And this is my view

@model ICollection<CustomModel>
<form asp-action="Index" asp-controller="Home" method="POST">
<table>
    @foreach (var m in Model)
    {
        <tr>
            <td><label asp-for="@Model">@m.Question</label><input asp-for="@m.Answer"/></td>
        </tr>
    }
</table>
<input type="submit" value="save" />

Example of how this would look when the page is renderd:

<tr>
            <td><label>Your name?</label><input type="text" id="m_Answer" name="m.Answer" value="" /></td>
        </tr>
        <tr>
            <td><label>Your Age?</label><input type="text" id="m_Answer" name="m.Answer" value="" /></td>
        </tr>

This is were i assumed it would have a index, but instead it looks like it treats each row as an induvidal model instead of a collection of models.

What am i doing wrong here? Is this a bug, or by design?

Github test project https://github.com/lasrol/TestModelBindingList

like image 621
Lasse Vabe Rolstad Avatar asked May 27 '16 18:05

Lasse Vabe Rolstad


1 Answers

Change your model to @model List<CustomModel> And than use next approach

<form asp-action="Index" asp-controller="Home" method="POST">
<table>
    @for (int i = 0; i < Model.Count; i++)
    {            
        <tr>
            <td>
                <input type="hidden" asp-for="@Model[i].Id" />
                <input type="hidden" asp-for="@Model[i].Question" />            
                <label asp-for="@Model[i].Question">@(Model[i].Question)</label>
                <input asp-for="@Model[i].Answer" />
            </td>
        </tr>            
    }
</table>
<input type="submit" value="save" />

So as you can see you should access to list items via index to properly render name attribute for inputs. Also do not forget to include other item properties via hidden inputs otherwise it values will be loosed in post action.

like image 154
YuriyP Avatar answered Sep 17 '22 22:09

YuriyP