O'Reilly logo

ASP.NET 4 24-Hour Trainer by Toi B. Wright

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

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

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