Creating Custom HTML Helpers

HTML Helpers

To modify HTML output in MVC, we opt to use HTML helpers that basically supports HTML controls rendering in a view.

HtmlHelper Class

It resides in the System.Web.Mvc namespace, responsible for rendering of HTML controls in our view.

The HtmlHelper type basically includes:

  • Constructors
  • Properties
  • Methods
  • Extension Methods
  • Fields

This section explains what HtmlHelper is and how a custom HtmlHelper can be created.

In ASP.NET we are very much familiar with webform controls. HTML Helpers work just like like those controls for MVC. HtmlHelpers are used to generate the UI in a view. They are not used in controllers or models.

Things to Remember

  • HtmlHelper are more lightweight than traditional ASP.NET controls.
  • HtmlHelper modifies HTML, used as a method that returns a string.
  • HtmlHelper does not have events to work with and viewstate property what we used to have with ASP.NET controls.

There are various built-in HtmlHelpers as well as we can create our own HtmlHelpers (custom HtmlHelpers).

Some of the existing HtmlHelpers are:

  • Html.ActionLink()
  • Html.TextBox()
  • Html.RadioButton()
  • Html.CheckBox()
  • Html.DropDownList()
  • Html.BeginForm()
  • Html.EndForm() 

Custom HtmlHelpers can be created in one of the following two ways:

  • Using Static Methods
  • Using Extension Methods

Using Static Method

We can create a static method that returns a string for creating a new HtmlHelper. Let's create a new HtmlHelper that renders a label tag of HTML as in the following:

  1. public class Helper  
  2. {  
  3.    public static string Label(string destination, string labeltext)  
  4.    {  
  5.       return string.Format(destination, labeltext);  
  6.    }  
  7. }  

Using Extension Method

HtmlHelpers created using extension methods that work just like other standard extension methpds in the ASP.NET MVC framework. By creating extension methods we are adding another method in HtmlHepler class that will be reflected in Html property of the view.

To add an extension method to the HtmlHelper class, we need to make that class static.

Let us say we are adding a method for a Label. We need to parameters indicating the class to which the extension class is extending. The other two parameters are just the same as what we saw when creating the HtmlHelper using a static method.

  1. public static class LabelExtentions  
  2.  {  
  3.      public static string Label(this HtmlHelper helper, string destination, string lbltext)  
  4.      {  
  5.          return string.Format(destination, lbltext);  
  6.      }  
  7.  }  


In this section I focused on the ways a custom HtmlHelper can be created and the rules for it. In future articles I will have more demostrations.

Resource: ASP.Net

Thanks for reading.

Up Next
    Ebook Download
    View all
    View all