MVC Custom HTML Helper Class

HTML helper class are predefined functions in MVC view which helps in generation of html code from Razor. It can be customized also. In this article we will  learn how to design a button with standard CSS class which can be maintained across the site using user defined helper class.

Create the following class “UserButton”.

  1. public class UserButton: IHtmlString   
  2. {  
  3.     private Button userButton = new Button();  
  4.   
  5.     public UserButton(string id, string text, IDictionary < stringobject > attributes)   
  6.     {  
  7.         userButton.Builder.AddCssClass("customBtn");  
  8.         userButton.Builder.SetInnerText(text);  
  9.   
  10.         if (attributes != null)   
  11.         {  
  12.             userButton.Builder.MergeAttributes(attributes);  
  13.         }  
  14.     }  
  15.   
  16.     public string ToHtmlString()   
  17.     {  
  18.         return this.ToString();  
  19.     }  
  20.   
  21.     public override string ToString()   
  22.     {  
  23.         return userButton.ToHtmlString();  
  24.     }  
  25. }  
Create an Extension method for HtmlHelper class and return the UserButton object.
  1. public static UserButton UserButton(this HtmlHelper html, string id, string text, object attributes)  
  2. {  
  3.    return new UserButton(id, text, new RouteValueDictionary(attributes));  
  4. }  
Call the extension method instead of the default method of the HtmlHelper button class.
  1. @Html.UserButton("btnClose","Cancel",new { @onclick = "window.close()" })  

 

Ebook Download
View all
Learn
View all