Creating Custom HTML Helpers Using MVC5

In this blog, I will show you how can you create your own custom HTML helper controls and modify them according to your need.

First things first


For example HTML helpers are those controls, which we use in the MVC view in the fashion mentioned below.

@Html.TextBox()

They render the UI in view. They are lightweight as compared to ASP.NET controls. Now, we will create our own helpers. Here, we simply create a static class with static method, which will return the MvcHtmlString to be used at the time of rendering.

Here is the function
  1. public static MvcHtmlString MyCustomLabel(string text) {  
  2.     var tagBuilder = new TagBuilder("label");  
  3.     tagBuilder.AddCssClass("myLabel");  
  4.     tagBuilder.InnerHtml = text;  
  5.     return new MvcHtmlString(tagBuilder.ToString());  
  6. }  
Here text is what you want to show on the label. myLabel is a css class, which I have written on view, so my entire helper class looks, as shown below.



In order to show you all the differences between custom and default label, I have used it in the view.

Entire

The output of the code is mentioned below.

Entire

Summary

In this blog, we have seen how to create your own custom helpers and modify them according to your need.

In future, I will have articles on more complex helper controls.
Ebook Download
View all
Learn
View all