4

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?

Bob.at.Indigo.Health
  • 11,023
  • 13
  • 64
  • 111

2 Answers2

7

You can use NameFor extension in MVC 4:

<div id="@Html.NameFor(m => m.Comment)">
polybios
  • 1,159
  • 8
  • 20
2

While I was going through the exercise of writing the question, I figured out the answer. As long as I've spent 20 minutes writing the question, I figure I might as well share the answer in case someone else wants to do the same thing.

To fabricate a name that contains a prefix that maps to the view model:

<div id="@ViewData.TemplateInfo.GetFullHtmlFieldName("something")">
    @Html.EditorFor(m => m.Comment)
</div>
Bob.at.Indigo.Health
  • 11,023
  • 13
  • 64
  • 111