A Beginner’s Guide to Creating Custom ASP.NET MVC HTML Helpers

Introduction

As a beginner, creating your own custom HTML Helpers might seem a bit daunting but it doesn’t have to be. Eventually, they boil down to simple HTML that all web developers are familiar with. In fact, HTML Helpers are very easy to create and the difficulty scales directly with the complexity of the problem you are trying to solve which is great news for the beginner. It means that you don’t have to learn a massive amount of information to start creating your own controls and your knowledge and sophistication can increase as you go.

What are HTML Helpers?

HTML Helpers are server-side extension methods that render HTML in the browser. They function like other extension methods by extending the functionality of System.Web.Mvc.HtmlHelper to enable our controls to function like the HTML Helper controls that are included by default in the MVC framework. This is exciting because the barrier to entry is so low. Anyone can create their own HTML Helpers or even entire libraries of helpers to be reused across many different projects.

Why Write Your Own?

There are several reasons you might want to create your own controls. Repetition or reuse comes to mind. If you find yourself creating the same functionality over and over, it might be a great candidate for a helper. For example, if you had to create a calendar in an application and needed to duplicate that calendar elsewhere in the same or different application, it would definitely be worthwhile to investigate converting that markup to an HTML Helper. Testability is another reason. Unit testing HTML Helpers is actually very simple because what comes out of the helper method is text in the form of an HtmlString.

Example: Custom Label Helper

It is quite easy to create your first custom HTML Helper. Here is a bit of sample code for an HTML Label control that accepts three arguments: the value of the control, the name of the control the label is tied to, and CSS classes to be applied to the control.

public static class LabelHelpers
{
  public static HtmlString CustomLabelFor(this HtmlHelper html, string text, string controlName, string cssClassName)
  {
    StringBuilder sb = new StringBuilder();

    sb.Append("<label");
    
    if(!string.IsNullOrEmpty(controlName))
    {
      sb.Append($" for='{controlName}'");
    }

    if(!string.IsNullOrEmpty(cssClassName))
    {
      sb.Append($" class='{cssClassName}'");
    }

    sb.Append($">{text}</label>");

    return new HtmlString(sb.ToString());
  }
}

As you can see, both the LabelHelpers class and the CustomLabelFor method are static. Additionally, because the method is an extension method, we are able to use the helper without instantiating, just like HTML Helpers built into the MVC framework. Through the method, we methodically build out the HTML required to render the label control in the page correctly.

Usage, then, becomes very simple.

<div class="row">
    <div class="col-md-12">
        @Html.CustomLabelFor("Hello", "World", "col-md-3")
        @Html.TextBox("World")
    </div>
</div>

Conclusion

This example is extremely simple. However, more sophisticated controls follow the same concept. You are simply building the HTML necessary for the control to render. It doesn’t really matter if this is a label or a calendar control. Approach the job of building your control systematically by tearing down the requirement piece by piece until you get to a point where you can immediately finish a small part of the requirement and build on that small part. Repeat until the control is completed.

Leave a Reply

Your email address will not be published.