Create custom HTML Helpers using MVC 4 Razor

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)

 

<system.web.webPages.razor>

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

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

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

<namespaces>

<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”/>

</namespaces>

</pages>

</system.web.webPages.razor>

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”)

 

OUTPUT :

 

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

Advertisements
By Sriramjithendra Posted in ASP.NET

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