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.

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:

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

Published by

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.

Loading Facebook Comments ...
Loading Disqus Comments ...