What is HTML Helper ?

The HTML helper is a method that returns a string. ASP.NET MVC Framework itself contains extension methods for HtmlHelper class to have well structured helper methods separation. Asp .Net MVC allow more flexible to extend the HelmHelper class to create our own custom helper method. It promote the use of reusable code.

  • HTML Helper methods will return string as output. if we want to write your own Html Helper method we have to create extension methods for HtmlHelper class.
  • System.Web.Mvc.Html contain the extension methods for Html Helper method.

Creating Custom Html Helper methods

Step : 1

Let’s create our extension methods for HTML Helper as like below.

From the above code, we creating CustomTextBox extender method which going to  return the appended string to the view.

Step : 2

Next step, we want to include our Html Helpers class namespace under the base class (ie., System.Web.Mvc.WebViewPage)

System.Web.Mvc.WebViewPage be the base class for the razor engine. So we want to refer the custom method under base class

Step : 3

Call our Custom Html Helper method in the index view as shown below. Our custom method accepting two parameter which is the name of the Input Type and value of the Input.

@Html.CustomTextBox(“custom_txtbox”,”Custom Helper Method”)

OUTPUT :

Run the application and view the source of the page in browser as shown below. Here the text box is generated using our custom helper method. We can call this Html Helper method any where with including custom attributes in it.

Creating Custom Html Helpers in mvc-dotnet-helpers