Home > ASP.NET MVC > Custom HTML Helper in MVC 4

Custom HTML Helper in MVC 4


If you have worked on MVC before then you must know that there are numbers of built in Html helper method are in MVC  like Html.ActionLink(),Html.RadioButton(),Html.TextArea(),Html.TextBox() etc .So When  a helper method is called in a View using the razor syntax @Html or <%= Html.LabelFor() , Then we actually using  the Html property of the View, which is an instance of the HtmlHelper class.

So to create a custom HTML Helper
— create extension methods for HtmlHelper class.
— System.Web.Mvc.Html contain the extension methods for Html Helper method.
So let’s Create an Custom Html Helper method

Step 1) create extension methods for HtmlHelper class.

namespace MVC4CustomHelper.Helper
{
    public static class CustomHelper
    {
        public static MvcHtmlString CustomTextBox(this HtmlHelper htmlHelper,string name,string value)
        {
            var builder = new TagBuilder("input");
            builder.MergeAttribute("type", "text");
            builder.MergeAttribute("name", name);
            builder.MergeAttribute("value", value);
            return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
        }

    }
}

Step 2) Taking reference in using View and using it

<%@ Import Namespace="MVC4CustomHelper.Helper" %>

Using created Custom Html Helper method

<%= Html.CustomTextBox("Name",Model.Name )%>

you will notice that it give Intellisense for Custom Html Helper method.
If you like this post the do not forget to like or comment on this 🙂

Advertisements
Categories: ASP.NET MVC Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: