Creating HTML helper in ASP.NET MVC


An HTML Helpers are method that returns a string (HTML). HTML Helpers can also be used to render more complex content such as a tab strip or an HTML table of database data.

In ASP.NET MVC we have few slandered HTML helper as:-
·         Html.ActionLink()
·         Html.BeginForm()
·         Html.CheckBox()
·         Html.DropDownList()
·         Html.EndForm()
·         Html.Hidden()
·         Html.ListBox()
·         Html.Password()
·         Html.RadioButton()
·         Html.TextArea()
·         Html.TextBox()

HTML helper can be created by 3 ways,
1. with Static Methods
2. with Extension Methods
3. with @helper (In Razor views only)

1. HTML helper with Static Method: - This is simplest approach to create custom helper, in this can simply create a static class with static method which will return the HTML.

In example below I am creating helper for textbox control with watermark text.

namespace HTMLHelpers
{
    public static class HTMLHelpers
    {
        public static IHtmlString TextBoxWithWaterMark(string WaterMarkcontent)
        {
            string htmlString = String.Format("<input type='text' placeholder={0}>", WaterMarkcontent);
            return new HtmlString(htmlString);
        }
    }
}

This HELPER can be used in view by just using/importing namespace HTMLHelpers

@using HTMLHelpers
@CustomHTMLHelpers.TextBoxWithWaterMark("WaterMarkText")


2. HTML helper with Extension Methods: - This are HTML helpers which will work just similar to slandered HTML helpers. Extension methods enable you to add new methods to an existing class. You do no need to import namespace in this case.

Extension method must be a static class and first parameter of an extension method indicates the class that the extension method extends.

    public static class HTMLHelpers
    {
        public static string TextBoxWithWaterMark(string WaterMarkcontent)
        {
            return String.Format("<input type='text' placeholder={0}>", WaterMarkcontent);
        }
    }


3. HTML helpers with @helper :- This is specific to Razor view only. In this we will create helper on view itself as shown in below code snippet.

@helper TextBoxWithWaterMark(string WaterMarkcontent)
{
    <input type='text' placeholder=@WaterMarkcontent>
}

Comments