JimFrenette.com

Razor Foreach Loop with Index

Written by Jim Frenette on November 21, 2012

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}))
		{
			
  • The index is @item.i and the value is @item.value.DisplayName
  • } } }

    Posted Under: Solutions

    About Jim Frenette

    I am a professional user interface engineer for a global digital marketing agency that builds connected brands for some of the world’s most recognized companies. The views presented on my blog are mine alone and do not represent my employers.

    One Response to “Razor Foreach Loop with Index”

    Leave a Reply

    You must be logged in to post a comment.


    Plugin from the creators ofBrindes Personalizados :: More at PlulzWordpress Plugins