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 needs.
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 a static method, which will return the MvcHtmlString to be used at the time of rendering.
Here is the function
- public static MvcHtmlString MyCustomLabel(string text) {
- var tagBuilder = new TagBuilder("label");
- tagBuilder.AddCssClass("myLabel");
- tagBuilder.InnerHtml = text;
- return new MvcHtmlString(tagBuilder.ToString());
- }
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 labels, I have used it in the view.
The output of the code is mentioned below.
Summary
In this blog, we have seen how to create your own custom helpers and modify them according to your needs.
In the future, I will have articles on more complex helper controls.