How To Create Custom HTML Helper in ASP.NET MVC? Here Is The Way. | Blowork

How To Create Custom HTML Helper in ASP.NET MVC? Here Is The Way.

In this article, I will explain how to create a custom HTML helper as per your requirement.

If you know the MVC and Helpers already, you can skip the next paragraph and if you don't know, here is an explanation about helpers.

What are HTML Helpers in MVC?

  • An HTML helper is a method that is used to render the specified html content in View. It can be implemented as an extension method.
  • If you know the ASP.NET webforms, you might know the concept of web controls. e.g. <asp:TextBox /><asp:label /> If you use these controls in web form on browsers, they will converted to their equivalent HTML controls like TextBox will be <input type="text" /> and label will be <span></span>
  • HTML helpers methods are the same as web controls it allows to render appropriate HTML in view.

Let's take an example of how HTML helper looks like:

@Html.TextBox("Myname","Mayur Lohite")

This HTML helper will render the following HTML in view.

<input type="text" name="Myname" id="Myname" value="Mayur Lohite" />

The MVC provides a rich set of HTML helpers, e.g. @html.TextBox(), @Html.TextArea(), @Html.CheckBox(), etc. but if you take a closer look in HTML Helpers, there is no helper present for Image tag i.e. <img src="" />

So in this tutorial, we will create our own custom helper for IMG tag

So we have to achieve something like:

@Html.MyImage("~/Image/mayur.jpg","Mayur Lohite" />

So, it will generate the following HTML.

<img src="/Image/mayur.jpg" alt="Mayur Lohite" />

If you take a closer look at @Html in view, it is a property of HtmlHelper class. Right click on @Html in view and click on Go to Definition. You will get the following output.

 

Now to create custom HTML helper, we need to create extension method of HtmlHelper class. So we can access our custom method by @Html property.

How to Create an Extension Method for HtmlHelper Class?

  • We have to create a static method in static class.
  • First parameter has to be the type to which we are adding the extension method. In our case, it is HtmlHelper Class.
  • Return type should be IHtmlString, as these strings are excluded from html encoding.
  • To create HTML tag, we have to use TagBuilder class
  • Include the namespace of the helper method in view or web.config

Here is the code: