DreamTeK
DreamTeK

Reputation: 34207

How to prevent generation of duplicate id fields in a foreach loop?

What is the procedure for generating unique element id's when iterating through a for each loop?

INPUT

@foreach (var x in Model.Class.Where(h => h.ID == 0))
{
  <form method="post">
    <input asp-for="@x.Field">
  </form>
}

Currently the asp-for tag will automatically generate an id from the model but it will create the same id for every element that is rendered within the loop.

OUTPUT

<input type="checkbox" data-val="true" id="x_Field" name="x_Field" checked="checked" value="true">

WITHOUT ASP-FOR

Or do I have to hardcore the html instead of using asp-for for iterating like this?

<input id="x[@x.Id].Field" checked="checked" />

Upvotes: 0

Views: 1184

Answers (1)

Mike Brind
Mike Brind

Reputation: 30045

If you want to retain the same value for the name attribute but have different values for the id attribute, you can pass an explicit value which will override the tag helper's generated value based on the property name:

@foreach (var x in Model.Class.Where(h => h.ID == 0))
{
  <form method="post">
    <input asp-for="@x.Field" id="@($"custom{x.ID}")">
  </form>
}

Upvotes: 2

Related Questions