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

Web Developer - views here are my own except those taken from people more clever than me.

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