Templates

Chapter 5 introduced templated helpers. The templated helpers are the subset of HTML helpers including EditorFor, and DisplayFor, and they are called the templated helpers because they render HTML using model metadata and templates. To jog your memory, imagine the following Price property on a model object.

        public decimal Price       { get; set; }

You can use the EditorFor helper to build an input for the Price property.

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

The resulting HTML will look like the following.

<input class="text-box single-line" id="Price"        name="Price" type="text" value="8.99" />

You've seen how you can change the output of the helper by adding model metadata in the form of data annotation attributes like Display and DisplayFormat. What you haven't seen yet is how to change the output by overriding the default MVC templates with your own, custom templates. Custom templates are powerful and easy, but before building any custom templates we'll show you how the built-in templates work.

The Default Templates

The MVC framework includes a set of built-in templates the templated helpers will use when constructing HTML. Each helper will select a template based on information about the model — both the model type and model metadata. For example, imagine a bool property named IsDiscounted.

public bool IsDiscounted { get; set; }

Again, you can use EditorFor to build an input for the property.

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

This time, the helper renders a checkbox input (compare ...

Get Professional ASP.NET MVC 3 now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.