Creating helpers using extension methods

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.

Note

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:

  1. Start by adding a new class file called ButtonExtensions.cs to the Helpers folder in the root of your project.
  2. Change the class type to static. Extension methods need to be declared inside a static class.
  3. Add a new method called BootstrapButton to the class. The first parameter of the method indicates which class the extension extends and must be preceded with the this keyword.
  4. The remaining parameters will be used to specify the caption, style, and size of the button. The code for the method is as follows:
            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.

Using the extension method helper in a view

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.212.212