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”.
- public class UserButton: IHtmlString
- {
- private Button userButton = new Button();
-
- public UserButton(string id, string text, IDictionary < string, object > attributes)
- {
- userButton.Builder.AddCssClass("customBtn");
- userButton.Builder.SetInnerText(text);
-
- if (attributes != null)
- {
- userButton.Builder.MergeAttributes(attributes);
- }
- }
-
- public string ToHtmlString()
- {
- return this.ToString();
- }
-
- public override string ToString()
- {
- return userButton.ToHtmlString();
- }
- }
Create an Extension method for HtmlHelper class and return the UserButton object.
- public static UserButton UserButton(this HtmlHelper html, string id, string text, object attributes)
- {
- return new UserButton(id, text, new RouteValueDictionary(attributes));
- }
Call the extension method instead of the default method of the HtmlHelper button class.
- @Html.UserButton("btnClose","Cancel",new { @onclick = "window.close()" })