How to determine model array index in editor template
asp.net-mvc, razor
Solution
You can use NameFor extension in MVC 4:
<div id="@Html.NameFor(m => m.Comment)">
Problem
My view model contains a list of Items, like this: ``` public class MyViewModel { public List<Item> Items { get; set; } } public class Item { public string Question { get; set; } public string Answer { get; set; } } ``` My view employs an editor template to render all of the Items. ``` @model MyApp.Models.MyViewModel @using (Html.BeginForm()) { @* Display all of the questions and answers *@ @Html.EditorFor(m => m.Items) } ``` and the Item.cshtml editor template renders each question and an editor for its associated answer: ``` @model MyApp.Models.Item @Html.TextBoxFor(m => m.Question) @Html.EditorFor(m => m.Answer) ``` In the rendered HTML, the EditorFor magic generates element names that include array notation that map to my model hierarchy, e.g.: ``` <input name="Items[0].Answer" ``` My question is: I want to render a `<div>` element whose id contains the same array index value in brackets, like this: ``` <div id="Items[0].something"> <something /> </div> ``` Is there an easy way for Item.cshtml to fabricate the id value, including the correct bracket notation?