What is HTML Helper ?
The HTML helper is a method that returns a string. ASP.NET MVC Framework itself contains extension methods for HtmlHelper class to have well structured helper methods separation. Asp .Net MVC allow more flexible to extend the HelmHelper class to create our own custom helper method. It promote the use of reusable code.
- 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 Custom Html Helper methods
Step : 1
Let’s create our extension methods for HTML Helper as like below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
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)); } } } |
From the above code, we creating CustomTextBox extender method which going to return the appended string to the view.
Step : 2
Next step, we want to include our Html Helpers class namespace under the base class (ie., System.Web.Mvc.WebViewPage)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<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> |
Step : 3
Call our Custom Html Helper method in the index view as shown below. Our custom method accepting two parameter which is the name of the Input Type and value of the Input.
@Html.CustomTextBox(“custom_txtbox”,”Custom Helper Method”)
OUTPUT :
Run the application and view the source of the page in browser as shown below. Here the text box is generated using our custom helper method. We can call this Html Helper method any where with including custom attributes in it.