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>


A month ago, MVC 3 was released. Given it’s maturity level and features, I have decided it’s time to start building web apps with it instead of web forms.

Get MVC 3.

Looking for jquery-1.4.4-vsdoc.js? Create a new MVC3 Web App (jquery-1.4.4-vsdoc.js)

Other jQuery files packaged in the project template include:

version 1.7 jQuery UI

Bonus – intellisense for the jQuery validation plug-in 1.7 (jquery.validate-vsdoc.js)

Razor HTML Helpers

I will expand/update this as I learn more about it. For now just a few examples that I wanted to document.
@using (Html.BeginForm("HandleForm", "Home")){ }

@using (Html.BeginForm("HandleForm", "Home", FormMethod.Post, new { id = "myForm" })){ }

@using (Ajax.BeginForm("HandleForm", "Home", new AjaxOptions { UpdateTargetId = "myResults" }, new { id = "myForm" })) { }

@Html.ActionLink("Detail", "Detail", new { controller = "Artist", id = 1 })

@Html.ActionLink("Detail", "Detail", new { controller = "Artist", id = 1 }, new { @class = "myClass", title = "My Link Title" })

@Html.ActionLink("Detail", "Detail", new { controller = "Artist", id = 1 }, new { id = "myId", title = "My Link Title" })

* Note the razor escape “@” before class. This is because “class” is reserved.

<form action="/Home/HandleForm" method="post"></form>

<form method="post" id="myForm" action="/Home/HandleForm"></form>

<form method="post" id="myForm" data-ajax-update="#myResults" data-ajax-mode="replace" data-ajax="true" action="/Home/HandleForm?Length=4"></form>

<a href="/Artist/Detail/1">Detail</a>

<a title="My Link Title" href="/Artist/Detail/1" class="myClass">Detail</a>

<a title="My Link Title" id="myId" href="/Artist/Detail/1">Detail</a>