Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 617
coolhand Avatar asked Sep 17 '25 11:09

coolhand


2 Answers

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.

like image 102
Anastasios Selmani Avatar answered Sep 20 '25 00:09

Anastasios Selmani


Use a for loop instead of foreach.

@for (int i = 0; i < Model.ItemList.Count(); i++)
{
    var item = Model.ItemList[i];
    <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>
}