What are HTML Helpers ? How to use HTML Helpers in ASP.NET MVC 3 using Razor ?

Why HTML Helper ?

Its a common need to generate the “same” block of HTML and Razor code, over and over again repeatedly in different views. Now writing this code over and over again can be tedious and error prone.

MVC Framework provides HTML Helpers to solve this problem.

How to use HTML Helpers in ASP.NET MVC 3 using Razor ?

Step 1 : Create a class “Helper.cs” as shown below. Make sure that the class and all its method are declared as static.


public static class Helper  
public static MvcHtmlString Greet(this HtmlHelper html)
string message = DateTime.Now.Hour < 12 ? "Good Morning." : "Good Afternoon.";
return new MvcHtmlString(message);  
The first parameter to a HTML helper method, will always be an HtmlHelper object with the this keyword.
Step 2 : To import the HTML helper into all your views, you have to include a reference in web.config of the Views folder.
<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.Routing" />
<add namespace="MvcApplication1.Utilities"/>
Step 3 : Now go to your view, and you will see the the HTML helper method that we have just created, as in the screenshot below...

Step 4 :