Create HtmlHelper Extension in MVC4
Hi Friends, Today I am going to demonstrate how we can create simple html helper class in mvc.
Introduction
HtmlHelper are simply a static class having extension methods that help you to render html tags using the @Html code.
This is helpful becuase you don't have to write html tag everytime of same type. you just need to simple code like @Html.LabelFor or @Html.Label. HtmlHelper are very simple to use
ASP.NET MVC has html helper methods for rendering html string like below
@Html.TextBox
@Html.TextBoxFor
@Html.Label
@Html.LabelFor
@Html.DropDownList
@Html.DropDownListFor
@Html.ActionLink
@Html.CheckBox
@Html.CheckBoxFor
@Html.BeginForm
@Html.EndForm
@Html.TextArea
@Html.ListBox
@Html.RadioButton
As their name suggest, these methods renders the html string. let us start to work around.
Practical Lab
1. First add a simple Asp.NET MVC application using Basic template as below show.
2. Create a directory named Helper in the root of your application. as below . Creating directory is optional to make the applicaion structured.
3. Now, to create the extension method we need to make the class static. Firstly, Import namespace System.Web.Mvc to access htmlhelper class.
I have crated a simple method MyTextBox with parameter this HtmlHelper helper to extend HtmlHelper and added some parameter Id, Name and Placeholder
that I will user to create the tag. As Below
In the above picture once extension class and method is created now I created input control using the tag builder class. Tag Builder class help us to create
html control and we can set different attributes using MergeAttribute mehtod. I have set Id, Name, Placeholder in this case.
4. Build the project once. Now go to the view where you want to render this html control. We need to import the namespace where we have defined the
HtmlHelperExtension Class and render your created control using @Html keyword. Like Below
5. At Last Press F5 and see the output of your program. Hopefully this sould look like below picture
I hope this might help you little bit for those who are starter to MVC.
Keep reading and spread love.
Thank you for reading.
CodeProject