I'm populating an HTML table with a collection of data items.
But I want each cell to be editable. And so I'm displaying the item fields in controls. For example:
@foreach (FleetRailcarDto railcar in editSection.Railcars)
{
<tr>
<td></td>
<td>
<select asp-for="@railcar.FleetId" asp-items="@Model.FleetOptions" >
</select>
</td>
<td>
<select asp-for="@railcar.Ownership" asp-items="@Model.OwnershipOptions" >
</select>
</td>
<td>
<input asp-for="@railcar.CarType" />
</td>
</tr>
}
This displays fine but it generates the same ID attributes for every table row.
I know I can build the HTML manually, but there are a few things going on here. Has anyone found a way to use asp-for
for variations of the same property without causing duplicate ID attributes?
CodePudding user response:
When binding to a collection for editing, you should use a for
loop instead of a foreach
loop to iterate the collection. That way you generate an indexer to group fields together. You also need a hidden field set to the identity value of each item:
@for (var i = 0; i < editSection.Railcars.Count;i )
{
<tr>
<td>
<input type="hidden" asp=for="editSection.Railcars[i].Id" />
</td>
<td>
<select asp-for="@editSection.Railcars[i].FleetId" asp-items="@Model.FleetOptions" >
</select>
</td>
<td>
<select asp-for="@editSection.Railcars[i].Ownership" asp-items="@Model.OwnershipOptions" >
</select>
</td>
<td>
<input asp-for="@editSection.Railcars[i].CarType" />
</td>
</tr>
}
More info here: https://www.learnrazorpages.com/razor-pages/model-binding#binding-complex-collections