Create Custom MVC 5 HTML Helper

An HTML Helper is a method that returns a string. The string can represent any type of content like standard HTML tags like HTML <input> and <img> tags. You also can use HTML Helpers to render more complex content such as a tab strip or an HTML table. We can either use standard\built-in helpers like Html.CheckBox(), Html.TextBox() or create our own helper.

Let’s create a new Visual Studio 2015 MVC 5 application and name it as HTMLHelperDemo,

HTMLHelperDemo

HTMLHelperDemo

We will a build a helper using C# extensions method on HtmlHelper class using TagBuilder class, which is used to create HTML elements. For more details on TagBuilder, refer here. We are using TagBuilder instead of StringBuilder, which avoids run-time errors like not closing a tag or invalid quotes within emitted HTML.

Create a folder, name it as Helpers than add a class HTMLButton.cs with below piece of code:

code

Here, I added CustomButton extension method on HtmlHelper class which will accept text, name and cssclass name for a button. Then, used TagBuilder to build HTML by using MergeAttribute for adding an attribute, AddCssClass method to add css class, GenerateId method to generate ID based on Name property and CreateSanitizedId method to set name attribute by removing spaces and special characters.

Let’s build the solution and use our helper in Home/Index.cshtml view as shown below:

code

Run the application and view source for rendered HTML:

application
application

Here, our helper added name, id (replaced space with _), css Class and Text for the button. By following above steps, we can create our own custom HTML helpers to reduce and centralize markup in our MVC views.

I attached source code and ending the things here on HTML helpers, I hope this article will be helpful for all.

Read more articles on MVC:

Up Next
    Ebook Download
    View all
    Learn
    View all