HTML Helpers

HTML helpers are methods you can invoke on the Html property of a view. You also have access to URL helpers (via the Url property), and AJAX helpers (via the Ajax property). All these helpers have the same goal: to make views easy to author. The URL helper is also available from within the controller.

Most of the helpers, particularly the HTML helpers, output HTML markup. For example, the BeginForm helper you saw earlier is a helper you can use to build a robust form tag for your search form, but without using lines and lines of code:

@using (Html.BeginForm("Search", "Home", FormMethod.Get)) {    
   <input type="text" name="q" />
   <input type="submit" value="Search" />
}

Chances are the BeginForm helper will output the same markup you had previously when you first implemented the search form. However, behind the scenes the helper is coordinating with the routing engine to generate a proper URL, so the code is more resilient to changes in the application deployment location.

Note the BeginForm helper outputs both the opening <form> and the closing </form>. The helper emits the opening tag during the call to BeginForm, and the call returns an object implementing IDisposable. When execution reaches the closing curly brace of the using statement in the view, the helper emits the closing tag, thanks to the implicit call to Dispose. The using trick makes the code simpler and elegant. For those who find it completely distasteful, you can also use the following approach, which provides ...

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.