Building HtmlHelper Extension Methods for ASP.NET MVC

Posted by: Malcolm Sheridan , on 10/27/2009, in Category ASP.NET MVC
Views: 62519
Abstract: The following article demonstrates how to create HtmlHelper extension method’s to use in your ASP.NET MVC application.
Building HtmlHelper Extension Methods for ASP.NET MVC
 
ASP.NET MVC is the latest buzz pattern in web development. ASP.NET MVC was recently released and I think it is a great way to develop web applications. If you are new to ASP.NET MVC, check ASP.NET MVC - Some Frequently Asked Questions and  Your First ASP.NET MVC Application. One of the benefits of MVC is you having total control over what and how your code is rendered in the browser. When you create the HTML for your page, a class that is very helpful is the HtmlHelper class. This class represents support for rendering HTML controls in a view. You can use the HtmlHelper class to render controls such as a TextBox, which renders as input type=”text”, to the browser like the following:
<%= Html.TextBox("Firstname") %>
In the first release of ASP.NET MVC, the HtmlHelper class does not cover a large area of HTML controls. This article will show you how to create your own extension method to complement the existing HtmlHelper class. Before going any further you’ll need to install ASP.NET MVC. You can download that here.

 

To begin with open Visual Studio 2008 and choose File > New > Project > ASP.NET MVC Web Application.
NewProject
 
By default Visual Studio creates several folders for you, namely Models, Views and Controllers. Start by creating a new folder in the root directory called Common. In that folder create a new class called Helpers and add the following code:
 
C#
 
public static class Helpers
{
       public static string Span(this HtmlHelper html, string text)
       {
            var builder = new TagBuilder("span");
            builder.GenerateId("firstName");
            builder.SetInnerText(text);
            return builder.ToString(TagRenderMode.Normal);
       }       
 }
 
VB.NET
 
Public Module Helpers
            <System.Runtime.CompilerServices.Extension> _
            Public Function Span(ByVal html As HtmlHelper, ByVal text As String) As String
                  Dim builder = New TagBuilder("span")
                  builder.GenerateId("firstName")
                  builder.SetInnerText(text)
                  Return builder.ToString(TagRenderMode.Normal)
            End Function
End Module
 
I’m using a feature in C# 3.0 called extension methods. Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Using this new feature allows you to write custom methods that will appear in Visual Studio’s intellisense when working in the HTML designer. The ASP.NET MVC framework includes a useful utility class named the TagBuilder class that you can use when building HTML helpers. The TagBuilder class, as the name of the class suggests, enables you to easily build HTML tags. The next step is to make this helper class available to all the Views in the project. You could add this directive to each view:
 
<%@ Import Namespace="MvcApplication1.Common" %>
 
But that would mean you would need to add this directive to every view that needs to use this helper class. That isn’t acceptable because of maintenance. What happens if you want to move it to another namespace? Allot of find and replaces! The better option is to add the namespace to the web.config file so it’s available to every view. Add the following code to the pages/namespaces element:
 
<add namespace="MvcApplication1.Common"/>
 
This helper class can now be used through the entire project. To demonstrate how to use this helper class you need to open the About.aspx in the Home view and add the following code:
 
<asp:Content ID="aboutContent" ContentPlaceHolderID="MainContent" runat="server">
    <h2>About</h2>
    <p>       
        <%= Html.Span("About page...") %>       
    </p>
</asp:Content>
 
In the code above there is the Span extension method created earlier. As you might expect it will render a <span> tag in the browser. Pretty neat huh?!
 

You can create helper methods that map to different HTML tags, so you can create them to display bold or even italic text. The choice is up to you. This is a nice feature of MVC that allows you to easily build custom HTML tags in your views. The entire source code of this article can be downloaded over here

Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Darryl on Wednesday, October 28, 2009 1:06 AM
When is MVC scheduled to be released?
I like reading your articles malcolm sheridan. Are you planning anything on asp.net 4.0?
Comment posted by Malcolm Sheridan on Wednesday, October 28, 2009 1:50 AM
@Darryl,
I'm glad you enjoy the articles.  MVC is released now so you can download it and play with it.  I am planning some future articles on ASP.NET 4.0 and MVC.
Comment posted by Darryl on Wednesday, October 28, 2009 3:35 AM
Isn't there a preview of mvc2 available in the market. Any information on the releasedate?

Can I be notified when new articles on asp.net 4 are added to this blog
Comment posted by Malcolm Sheridan on Wednesday, October 28, 2009 4:09 AM
@Darryl,
Yes MVC beta 2 is available now too.  I don't know of an official release date yet.  If you subscribe to the RSS feeds you'll know when new articles are released here.
Comment posted by Shayne on Saturday, October 31, 2009 6:14 AM
Thanks for explaining it so well
Comment posted by Matt on Monday, November 2, 2009 9:58 AM
Just curious, why do you set the span ID to firstName?
Comment posted by Malcolm Sheridan on Monday, November 2, 2009 3:48 PM
@Matt
I set the id to that so that span can be referenced as firstName.  You can pass in any value you like.

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel