O'Reilly logo

Professional ASP.NET MVC 4 by Scott Hanselman, K. Scott Allen, Brad Wilson, Phil Haack, Jon Galloway

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Advanced 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required