Chapter 10B. Custom HTML Helpers in MVC

There is a large set of HTML Helpers that come with the ASP.NET MVC framework. Nevertheless, you can write your own custom HTML Helpers. In this lesson I show you how to write both a simple HTML Helper and how to write an HTML Helper using an extension method.

CREATING AN HTML HELPER

The ASP.NET MVC framework does not come with an HTML Helper to generate an ordered list. This is the HTML for a sample ordered list:

<ol>
    <li>Item One</li>
    <li>Item Two</li>
    <li>Item Three</li>
</ol>

The following class builds a string to output an MvcHtmlString that contains the HTML required to render an ordered list:

public class OrderedListHelper
{
    public static MvcHtmlString OrderedList(Object items)
    {
       var builder = new StringBuilder();
       builder.Append("<ol>");
       var enumItems = (IEnumerable<Object>)items;
       foreach (Object item in enumItems)
           builder.AppendFormat("<li>{0}</li>",
               HttpUtility.HtmlEncode(item.ToString()));
       builder.Append("</ol>");
       return MvcHtmlString.Create(builder.ToString());
     }
}

Note

An MvcHtmlString is an HTML-encoded string that should not be encoded again.

This is the code the view uses to call this new static method:

<%: OrderedListHelper.OrderedList(ViewData.Model) %>

CREATING AN HTMLHELPER EXTENSION METHOD

A better way to create a new HTML Helper is to use an extension method. An extension method is a new method for an existing class, and in order to create one you need to do two things:

  1. Create a static class with a static method.

  2. Set the type of the ...

Get ASP.NET 4 24-Hour Trainer 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.