Create Custom HTML Helpers in ASP.Net MVC

HTML Helpers are classes that helps to render HTML controls in Views. We can also create our own HTML Helpers. In this post, I’m going to explain how to create a simple Custom HTML Helper. The main purpose creating custom HTML helper is reuseability.

Step 1
 
Create a static class and add method to it like below.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. namespace MVCTutorial  
  7. {  
  8.     public static class CustomHTMLHelper  
  9.     {  
  10.         public static MvcHtmlString ImageLink(string action, string controller, string imgageURL)  
  11.         {  
  12.             // Create a link with an image    
  13.             return MvcHtmlString.Create(String.Format("<a href=\"{1}\\{0}\"> <img src=\"{2}\" /></a>", action, controller, imgageURL));  
  14.         }  
  15.     }  
  16. }  
Step 2
 
Access the custom helper class in a View.
  1. <!DOCTYPE html>    
  2. <html>    
  3. <head>    
  4.     <meta name = "viewport" content="width=device-width" />    
  5.     <title>Sample</title>    
  6. </head>    
  7. <body>    
  8.     <div>    
  9.         @CustomHTMLHelper.ImageLink("Home","Account","your image url")    
  10.     </div>    
  11. </body>    
  12. </html>