Templated Helpers in MVC

The templated helpers in ASP.NET MVC build HTML using metadata and a template. The metadata includes information about a model value (its name and type), as well as model metadata (added through data annotations or a custom provider). The templated helpers are Html.Display and Html.Editor, their strongly typed counterparts, Html.DisplayFor and Html.EditorFor, and their whole-model counterparts, Html.DisplayForModel and Html.EditorForModel.
As an example, the Html.TextBoxFor helper renders the following HTML for an album’s Title property:

<input id="Title" name="Title" type="text" value="For Those About To Rock We Salute You" />

Instead of using Html.TextBoxFor, you can switch to using the following code:

@Html.EditorFor(m => m.Title)

The EditorFor helper will render the same HTML as TextBoxFor; however, you can change the HTML using data annotations. If you think about the name of the helper (Editor), the name is more generic than the TextBox helper (which implies a specific type of input element). When using the templated helpers, you are asking the runtime to produce whatever “editor” it sees fi t. Let’s see what happens if you add a Data Type annotation to the Title property:

[Required(ErrorMessage = "An Album Title is required")]
[StringLength(160)]
[DataType(DataType.MultilineText)]
public string Title { get; set; }

Now the EditorFor helper renders the following HTML:

<textarea class="text-box multi-line" id="Title" name="Title">Let There Be Rock</textarea>

Since you asked for an editor in the generic sense, the EditorFor helper looked at the metadata and determined that the best HTML element to use was the textarea element (because the metadata indicates the Title property can hold multiple lines of text). Of course, most album titles won’t need multiple lines of input, although some artists do like to push the limit with their titles.
The DisplayForModel and EditorForModel helpers build the HTML for an entire model object. Using these helpers, you can add new properties to a model object and instantly see changes in the UI without making any changes to the views.

Tagged . Bookmark the permalink.

Leave a Reply