ASP.NET MVC: Creating Custom HTML Helper Methods

Introduction

In this article we will learn how to create custom HTML helper methods and the various ways of doing it in an ASP.NET MVC framework application. HTML helper methods play important role in developing the views of an ASP.NET MVC application. It is known that the ASP.NET MVC application is controller driven i.e. the controller is responsible for rendering the respective view, during this rendering process the controller internally takes care of executing the HTML Helper methods on the view.

As the name suggests these are simply helper methods which a developer can use to render the HTML elements like textbox, checkbox, form, validation summary, etc and also can call methods like Validate for validating a model, encode for HTML encoding a string, etc. Some of the built-in HTML Helper methods are listed below:

  1. Html.ActionLink
  2. Html.Validate
  3. Html.ValidateFor<>
  4. Html.TextBox
  5. Html.TextBoxFor<>,  etc

By seeing the above list you will also notice that generic HTML Helper methods are also available. So what is the advantage of using these HTML helper methods?

  1. Re-usability, the developer can use these helper methods across multiple views.
  2. Less coding effort, the developer simply has to make a call to the HTML helper method for the view to be rendered with desired HTML content.
  3. Extensibility, yes the developer can build his own HTML helper method which we will be learning through this article.
  4. A means to call the server side method from a view or a partial view while rendering.

Creating Custom HTML Helper Methods

ASP.NET MVC framework allows you to write custom HTML Helper methods. HTML Helper methods will be written either in C# programming or in VB.NET as they will be executed on the server side. There are two prominent ways of doing it.

  1. Static Method
  2. Extension Method

In your ASP.NET MVC application create a separate library for the custom HTML helper methods. Add a .cs file to the library and name it as ContainerHelper.cs. In that file create two classes ContainerHelperStatic and ContainerHelperExtension. For illustration purposes I will create a custom HTML helper method to render a div container holding few HTML elements. The HTML helper method should basically accept the parameters required to build the HTML content and return a string value which should be the manipulated HTML content. I will provide samples using both static and extension methods in order to create custom HTML helper methods.

Static Method

If you want to create the HTML helper method using a static method then in the ContainerHelperStatic class create a static method called Container. Below is the C# programming code.

  public static string Container(string divCssClass, string labelText, string labelCss, string anchorUrl, string anchorText)
  {
      TagBuilder divTag = new TagBuilder("div");
      divTag.AddCssClass(divCssClass);
      TagBuilder labelTag = new TagBuilder("label");
      labelTag.AddCssClass(labelCss);
      labelTag.SetInnerText(labelText);
      TagBuilder anchorTag = new TagBuilder("a");
      anchorTag.MergeAttribute("href", anchorUrl);
      anchorTag.SetInnerText(anchorText);
      divTag.InnerHtml = string.Format("{0}<br/><br/><br/>{1}", labelTag.ToString(), anchorTag.ToString());
      return divTag.ToString();
  }

Extension Method

If you want to create the HTML helper method using an extension method then in the ContainerHelperExtension class create an extension method called Container. Below is the C# code.

  public static string Container(this HtmlHelper htmlHelper, string divCssClass, string labelText, string labelCss, string anchorUrl, string anchorText)
  {
              TagBuilder divTag = new TagBuilder("div");
              divTag.AddCssClass(divCssClass);
              TagBuilder labelTag = new TagBuilder("label");
              labelTag.AddCssClass(labelCss);
              labelTag.SetInnerText(labelText);
              TagBuilder anchorTag = new TagBuilder("a");
              anchorTag.MergeAttribute("href", anchorUrl);
              anchorTag.SetInnerText(anchorText);
              divTag.InnerHtml = string.Format("{0}<br/><br/><br/>{1}", labelTag.ToString(), anchorTag.ToString());
              return divTag.ToString();
  }

In the above code snippets you would notice a new class called TagBuilder. It is specifically introduced to facilitate developers in building the HTML content easily in ASP.NET MVC framework applications. This class is ingrained in the library System.Web.Mvc. So in order to use the TagBuilder class, reference of System.Web.Mvc library has to be added to the project.



ASP.NET MVC: Creating Custom HTML Helper Methods

Using Custom HTML Helper Methods in Views

As we have created the HTML helper methods now let us peek into using the custom HtmlHelper method in a view. Check out the below steps.

  1. Since the HTML helper methods are created in a separate class library as a first step add the reference of the library to the web application.
  2. Open the view in which the HTML helper has to be used and add the below tag after the page directive in order to import the namespace under which the HTML helper class exist. Once the namespace is imported the view will be enriched with the intellisence for the available custom HTML helper methods.

      <%@ Import Namespace="CodeGuru.Article.CustomHtmlHelpers" %>
    

  3. In order to use the html helper created using a static method you should make use of the class name as shown below.

      <%= ContainerHelperStatic.Container("divCssClass", "Custom HTML Helper using Static method", "labelCssClass", "http://www.codeguru.com", "Go to CodeGuru.com") %>
    

  4. In order to use the HTML helper created using an extension method you should make use of the built-in HtmlHelper class as shown below.

      <%= Html.Container("divCssClass", "Custom Html Helper using Extension method", "labelCssClass", "http://www.internet.com", "Go to Internet.com") %>
    

  5. That's it we are ready to go. Below is the client side code of the sample view.

      <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
      <%@ Import Namespace="CodeGuru.Article.CustomHtmlHelpers" %>
    

  6.   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      
      <html xmlns="http://www.w3.org/1999/xhtml" >
      <head runat="server">
          <title>Index</title>
          <style type="text/css">
          .divCssClass
          {
          	border-style:solid;
          	border-width:thin;
          	background-color:Black;
          	width:300px;
          	height:150px;
          }
          
          .labelCssClass
          {
          	color:White;
          	font-size:12;
          	font-weight:bold;
          }
          </style>
      </head>
      <body>
          <div>
              <%= ContainerHelperStatic.Container("divCssClass", "Custom Html Helper using Static method", "labelCssClass", "http://www.codeguru.com", "Go to CodeGuru.com") %>
              <br />
              <%= Html.Container("divCssClass", "Custom Html Helper using Extension method", "labelCssClass", "http://www.internet.com", "Go to Internet.com") %>
          </div>
      </body>
      </html>
    

    Run the application and check out the output rendered on the browser. Two div containers will show up one rendered by the static HTML helper method and other rendered by the extension HTML helper method. Fig 1.0 shows the output screen.

    [htmlhelp1.jpg]
    Fig 1.0

    Conclusion

    Hope this article covers the steps involved in creating custom HTML helpers in an ASP.NET MVC application. Please feel free to make use of the comments section for providing your feedback or to ask questions.

    Happy Reading!

    Related Articles





About the Author

V.N.S Arun

I work for an MNC in Bangalore, India. I am fond of writing articles, posting answers in forums and submitting tips in dotnet. To contact me please feel free to make use of the "Send Email" option next to the display name.

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Download the Information Governance Survey Benchmark Report to gain insights that can help you further establish business value in your Records and Information Management (RIM) program and across your entire organization. Discover how your peers in the industry are dealing with this evolving information lifecycle management environment and uncover key insights such as: 87% of organizations surveyed have a RIM program in place 8% measure compliance 64% cannot get employees to "let go" of information for …

  • With JRebel, developers get to see their code changes immediately, fine-tune their code with incremental changes, debug, explore and deploy their code with ease (both locally and remotely), and ultimately spend more time coding instead of waiting for the dreaded application redeploy to finish. Every time a developer tests a code change it takes minutes to build and deploy the application. JRebel keeps the app server running at all times, so testing is instantaneous and interactive.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds