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.

Helper.cs

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.

<system.web.webPages.razor>  
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.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.Routing" />  
    <add namespace="MvcApplication1.Utilities"/>  
    </namespaces>  
    </pages>  
</system.web.webPages.razor>  

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…

Index.cshtml

<p>  
@Html.Greet()  
</p>  

Step 4 :

Output