coolhand
coolhand

Reputation: 2061

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.

Upvotes: 4

Views: 10088

Answers (2)

Anastasios Selmani
Anastasios Selmani

Reputation: 3689

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.

Upvotes: 8

user1023602
user1023602

Reputation:

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>
}

Upvotes: 2

Related Questions