[ASP.NET Core] Precautions when creating a list format input screen using HTML helper

less than 1 minute read

Precautions when using HTML helper in input screen and List type class

When I tried to create a screen to receive post data with a List type class by inputting multiple lines with table tags using HTML helper in ASP.NET Core (MVC), the input data was not posted and I was addicted to it.

The conclusion is OK if you do it with a normal for instead of foreach

NG
It will not be posted if it is foreach

@foreach (var row in Model.Rows)
{
<tr>
    <td>@Html.EditorFor(m => row.ColA)</td>
    <td>@Html.EditorFor(m => row.ColB)</td>
</tr>
}

OK
OK with for

@for(var i = 0; i < Model.Rows.Count; i++)
{
<tr>
    <td>@Html.EditorFor(m => m.Rows[i].ColA)</td>
    <td>@Html.EditorFor(m => m.Rows[i].ColB)</td>
</tr>
}