If we want our helpers to behave in a manner similar to the built-in ASP.NET MVC HTML Helpers, we need to create an extension method. Extension methods are a technique used to add new methods to an existing class.
Extension methods are a very powerful and intuitive approach to add additional functionality to existing classes and can help you in many ways. You can read more about extension methods on MSDN at http://bit.ly/ExtMethods.
We'll create an extension method to the HtmlHelper
class that is represented by a view's HTML property by completing the following steps:
ButtonExtensions.cs
to the Helpers
folder in the root of your project.static
. Extension methods need to be declared inside a static class.BootstrapButton
to the class. The first parameter of the method indicates which class the extension extends and must be preceded with the this
keyword.public static IHtmlContent BootstrapButton(this IHtmlHelper helper, string caption, Enums.ButtonStyle style, Enums.ButtonSize size) { if (size != Enums.ButtonSize.Normal) { return new HtmlString(string.Format("<button type="button" class="btn btn-{0} btn-{1}">{2}</button>", style.ToString().ToLower(), ToBootstrapSize(size), caption)); } return new HtmlString(string.Format("<button type="button" class="btn btn-{0}">{1}</button>", style.ToString().ToLower(), caption)); }
The BootstrapButton
method is the same as the Button
method in the ButtonHelper
class we created earlier, apart from the fact that it is an extension to the IHtmlHelper
interface.
As the BootstrapButton
method is an extension method, using it involves opening the view and adding the following markup to it:
@using Chapter5.Helpers <div class="row"> @Html.BootstrapButton("My Button", Enums.ButtonStyle.Info, Enums.ButtonSize.Normal) </div>
Note that we're using the standard HTML Helper to invoke the BootstrapButton
method.
3.137.212.212