How to create custom HTML Helpers using MVC 4 Razor

Note : Hi guys please visit new website for future posts Thanks for support

Creating custom HTML Helpers using MVC 4 RAzor

  • HTML Helper methods will return string as output. if we want to write your own Html Helper method we have to create extension methods for HtmlHelper class.
  • System.Web.Mvc.Html contain the extension methods for Html Helper method.

Creating own Html Helper methods

Razor pages uses System.Web.Mvc.WebViewPage type as base class.

Step : 1

Let’s create our extension methods for HTML Helper.

namespace CustomHelpers
public static class HtmlHelperExtensions
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));

Here we creating CustomTextBox extender method.. It will return the appended string to the view

Step : 2

Next step, we want to add namespace under the base class (ie., System.Web.Mvc.WebViewPage)


<host factoryType=”System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc,

Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35″ />

<pages pageBaseType=”System.Web.Mvc.WebViewPage”>


<add namespace=”System.Web.Mvc” />

<add namespace=”System.Web.Mvc.Ajax” />

<add namespace=”System.Web.Mvc.Html” />

<add namespace=”System.Web.Optimization”/>

<add namespace=”System.Web.Routing” />

<add namespace=”CustomHelpers”/>




System.Web.Mvc.WebViewPage be the base class for the razor engin.. so we want to refer the custom method under base class

Step : 3

Call our Custom Html Helper method in the index. As created pass two parameter to the custom Helper Method

@Html.CustomTextBox(“custom_txtbox”,”Custom Helper Method”)



Created Custom TextBox  as show below

How to create custom HTML Helpers using MVC 4 RAzor

As passed parameter @Html.CustomTextBox(“custom_txtbox”,”Custom Helper Method”) , 

it create value as “Custom Helper Method” and  ” Custom_txtbox” as name of the textbox

How to create custom HTML Helpers using MVC 4 RAzor 1


2 thoughts on “How to create custom HTML Helpers using MVC 4 Razor

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s