Search code examples
c#razorasp.net-core

Increment an Index Counter in Razor


I have a View model that has an IEnumerable object that I loop through to display a data table. The model also has an array of values that I would like to display within the same table.

The enumerable data is displayed with a foreach loop. I've tried adding an index counter to loop through the array on the same table, but the counter never increments. How can I combine both elements in the same table?

        //my foreach loop goes through my Item List
        @foreach (var item in @Model.ItemList)
        {
            //i need an indexer to go through MyArray
            var i = 0;
            <tr>
                <td>@Html.DisplayFor(shortDate => item.StartDate)</td><td>@Html.DisplayFor(shortDate => item.EndDate)</td><td>@Model.MyArray[i]</td><td>@item.Value</td>
            </tr>
            //here the index 'i' never seems to increment
            i++;
        }

The result is that only MyArray[0] value is displayed for all rows.


Solution

  • Every time the code gets inside the loop your "i" gets set to zero. You have to initialize your counter outside of the loop like this:

    @{
        // Here the initialization happens outside of the loop
        var i = 0;
    } 
    
    @foreach (var item in @Model.ItemList)
    {      
        <tr>
            <td>@Html.DisplayFor(shortDate => item.StartDate)</td><td>@Html.DisplayFor(shortDate => item.EndDate)</td><td>@Model.MyArray[i]</td><td>@item.Value</td>
        </tr>
        //here your index should increment correctly
        i++;
    }
    

    Otherwise, you can find your index just by this:

    int index = @Model.ItemList.IndexOf(item);
    <tr>
        ...
        <td>
          @index
        </td>
        ...
    </tr>
    

    inside your loop.