Blog

HTML Helper Classes

Excerpt by James Curtis | September 17, 2013

HTML helpers are implemented in the System.Web.Mvc.HtmlHelper and HtmlHelper<T> classes. Views and partial views in MVC have an Html property that expose an HtmlHelper class, making it easy to use in a view. If you examine the interface of the HtmlHelper class in the documentation, you'll find that it doesn't implement most of the helper methods as native methods on the class. Instead, most of the helpers are extension methods implemented in the System.Web.Mvc.Html namespace, and HtmlHelper merely functions as an anchor point for those helpers. Although HtmlHelper is most useful as the source of the helper extension methods, it has a number of its own native methods, of which Table 1 lists a few.

MethodDescription
AntiForgeryTokenAdds a hidden form field with an anti-forgery token, used to defend against cross-site request forgery (CSRF) attacks. You can also extend this by passing in a salt value, domain and path.
AttributeEncodeHTML-encodes an attribute value.
EnableClientValidationTurns on client-side validation, causing the helpers to generate the necessary client-side code.
EncodeHTML-encodes a string or object value passed to the method.
HttpMethodOverrideReturns the value of a hidden field that identifies an override method for the HTTP data-transfer method used by the client.

 

Table 1. Some useful native methods of HtmlHelper. The native HTML helpers included with HtmlHelper and its extension methods are useful, but cover only the most commonly used HTML elements. You'll probably find yourself wanting more, and it is relatively easy to write your own helper methods, or even throw away the built-in helpers and use your own custom helper methods instead. Then, instead of referencing the System.Web.Mvc.Html namespace in your project, you replace it with your namespace with your custom helper extension methods. This is just another way that you're in control in MVC. Types of HTML Helper Methods MVC includes three broad classes of HTML helper methods: untyped helper methods, strongly-typed helper methods, and templated helpers. The untyped helper methods first appeared in the initial release of MVC, version 1, and generally take a string with the name of the property to which it is bound at runtime. The following code is an example of using a regular HTML helper to display a label, text box, and validation message to edit a Name property of the view model object, using the Label, TextBox, and ValidationMessage helper methods.

  @Html.Label("Name") @Html.TextBox("Name") @Html.ValidationMessage("Name")

A strongly-typed helper has "For" appended to the name of the method and takes a lambda expression that binds the helper to a model property at design time. This is in contrast to a regular helper that takes a string parameter. Strongly-typed helpers have the benefit of catching many kinds of problems at compile time instead of runtime, and IntelliSense fully supports them when you write code. The following code is an example of using strongly-typed helpers for the same Name property of the previous code, using the LabelFor, TextBoxFor, EditorFor and ValidationMessageFor methods. Notice that each takes a lambda expression to bind the helper at design time.

 
@Html.LabelFor(model => model.Name)
@Html.TextBoxFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name)

@Html.EditorFor(model => model.Notes) @Html.ValidationMessageFor(model => model.Notes)

Using a lambda expression lets you pass both the field that the helper is binding to and the value of the field. The strongly-typed helper method uses this information to intelligently determine how to display the data. It really is a rather elegant way to pass the information to the helper method.

TIP: Try misspelling a field name to see what happens. Specifically, misspell one of the field names in one of the TextBox helper methods in the Edit view of the AWLTProducts project, such as changing "Name" to "Nam." You'll find that when you edit a product's data you will receive a Compilation Error since the Product model does not contain a definition for "Nam".

Code that uses strongly-typed methods looks a bit more complex and requires more typing than the untyped versions, but only a little. And because the fields you are using are strongly typed, IntelliSense can help you where it couldn't with just strings, as shown in Figure 12. Another benefit of using stronglytyped helper methods is that refactoring tools can update the views if you change field names.

figure12intellisense

Figure 12. IntelliSense provides a list of the properties of the Product object.Templated helpers take the methods to an entirely different level, using built-in and custom templates to give you fine control over the HTML generated based on various templates. You can even throw an entire custom object at a templated helper, and the helper will use reflection to render all its properties-including nested properties-based on the templates defined for each data type, and reverting to a text box for any data types for which it has no template. The following code is an example of using a template helper to edit an entire view model, not just a single property of the object, using the EditorForModel method.

 @Html.EditorForModel()

James CurtisThis post is an excerpt from the online courseware for our MVC4.0: Working with Data course written by expert James Curtis.



James Curtis

James Curtis is a .NET Developer that primarily works in the UX space. He has worked on and for several large projects alongside Microsoft Consulting. James has spoken at several code camps about UX development for ASP.NET and SharePoint. He is an active participant in the development community tweeting and blogging about several topics in the UX area. James is an active consultant and is also assisting in several Start-ups contributing his UX experience.


This course excerpt was originally posted September 17, 2013 from the online courseware MVC 4.0, Part 04 of 11: Working with Data by James Curtis