The simplest way to create a helper in ASP.NET MVC used to be the @helper
directive. Unfortunately, the @helper
directive was removed from the new ASP.NET MVC Core, since it imposed too many restrictions on the other Razor features.
Fortunately, we're still able to create an HTML Helper using static method by completing the following steps:
Helpers
inside the root folder of your project.Enums.cs
. This file will contain all the enumerators for our project.Enums.cs
file:public class Enums { public enum ButtonStyle { Default, Primary, Secondary, Success, Info, Warning, Danger } public enum ButtonSize { Large, Small, ExtraSmall, Normal } }
ButtonHelper.cs
in the Helpers
folder.Button
to the ButtonHelper
class, and add the following code to it:public static HtmlString Button(string caption, Enums.ButtonStyle style, Enums.ButtonSize size) { if (size != Enums.ButtonSize.Normal) { return new HtmlString( $"<button type="button" class= "btn btn-{style.ToString().ToLower()} btn-{ToBootstrapSize(size)}">{caption}</button>"); } return new HtmlString( $"<button type="button" class="btn btn-{style.ToString().ToLower()}">{caption}</button>"); }
ToBootstrapSize
:private static string ToBootstrapSize(Enums.ButtonSize size) { string bootstrapSize = string.Empty; switch (size) { case Enums.ButtonSize.Large: bootstrapSize = "lg"; break; case Enums.ButtonSize.Small: bootstrapSize = "sm"; break; case Enums.ButtonSize.ExtraSmall: bootstrapSize = "xs"; break; } return bootstrapSize; }
The Button
method we created earlier accepts three parameters in order to set the button's caption, size, and style. We used the enumerator values declared in the Enums.cs
file in order to list the available sizes and styles for the button, this releases the developer from memorizing the exact Bootstrap class names for each.
The Button
method returns an HtmlString
object that represents an HTML-encoded string, which does not need to be encoded again. If we simply return a normal string object, the actual HTML would be rendered inside the view instead of the button.
The ToBootstrapSize
method basically converts the ButtonSize
value to a valid Bootstrap class name that represents the size of the button.
In order to use the static method helper we created earlier, open the view you intend to use it in, and add the following Razor markup to it:
<div class="row"> @ButtonHelper.Button("Large Danger Button", Enums.ButtonStyle.Danger, Enums.ButtonSize.Large) </div> <div class="row"> @ButtonHelper.Button("Normal Info Button", Enums.ButtonStyle.Info, Enums.ButtonSize.Normal) </div> <div class="row"> @ButtonHelper.Button("Small Secondary Button", Enums.ButtonStyle.Secondary, Enums.ButtonSize.Small) </div>
The result will look similar to the following screenshot:
3.139.83.62