0

I am generating multi Data entry Line using ASP MVC , however looking at the HTML source after generating by MVC, I've just noticed those HTML elements has a duplicated ID , even with the same html type it is look something wrong ? is that normal behavior in MVC and how to avoid it ? , I need really to have it unique, assuming MVC should handle the ID generation for multi line, which is additional concern to me . My code :

  @foreach (var item in Model.lstMeals)
    {
        <tr>


            <td>
                <input asp-for="@item.cuisine.CuisineName" />
                @Html.DisplayFor(modelItem => item.cuisine.CuisineName)
            </td>


        </tr>
    }

then looking in HTML Source :

 <tr>
               
               
                <td>
                    <input type="text"  id="item_cuisine_CuisineName" name="item.cuisine.CuisineName" value="Italian" />
                    Italian
                </td>
               
              
            </tr>
            <tr>
               
               
                <td>
                    <input type="text" id="item_cuisine_CuisineName" name="item.cuisine.CuisineName" value="French" />
                    French
                </td>
               
              
            </tr>
            <tr>
               
               
                <td>
                    <input type="text" id="item_cuisine_CuisineName" name="item.cuisine.CuisineName" value="Greek" />
                    Greek
                </td>
               
              
            </tr>
JPNN
  • 383
  • 1
  • 7
  • 23
  • You cannot use a `foreach` loop to generate for, controls for a collection, and you will not be able to bind to your model when you submit the form. You need a `for` loop (or `EditorTemplate`) - refer [this answer](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943) –  Jun 06 '18 at 21:49

2 Answers2

0

If you use tag-helper within a loop, it won't generate an unique id for you for each element It doesn't have a context of the index position within the loop.

With that said, you can easily generate your own unique id "algorithm" for your HTML elements inside the loop with usage of the index:

@for(int i = 0; i < Model.lstMeals.Count(); i++)
{
    <tr>
        <td>
            <input asp-for="@Model.lstMeals[i].cuisine.CuisineName"
                type="text"
                id="xxx-xxx-lstmeals-@i" />
        </td>
    </tr>
}
David Liang
  • 20,385
  • 6
  • 44
  • 70
0

I think you can do it with for loop something like this.

@for (int i = 0; i < Model.lstMeals.Count; i++) 
{
    <tr>
        <td>
            <input asp-for="@Model.lstMeals[i].item.cuisine.CuisineName[i]" />
            @Html.DisplayFor(modelItem => item.cuisine.CuisineName)
        </td>
    </tr>
}
Murat Gündeş
  • 852
  • 2
  • 17
  • 31