Razor Foreach Loop with Index
I recently needed to get the index of an item in a razor foreach loop. This simple solution posted as a comment by Ian Mercer on Phil Haack’s blog did the trick easily.
Models/NameModel.cs
public class NameModel
{
public int Id { get; set; }
public string DisplayName { get; set; }
}
If we have a model called NameModel with a string DisplayName being returned to our view as a list object:
Views/Home/View.cshtml
@model List
@{
if (Model != null)
{
//this gets you the item (item.value) and its index (item.i)
foreach (var item in Model.Select((value,i) => new {i, value}))
{
<li>The index is @item.i and the value is @item.value.DisplayName</li>
}
}
}