Reader small image

You're reading from  Bootstrap for ASP.NET MVC - Second Edition

Product typeBook
Published inSep 2016
Reading LevelIntermediate
Publisher
ISBN-139781785889479
Edition2nd Edition
Languages
Right arrow
Author (1)
Pieter van der Westhuizen
Pieter van der Westhuizen
author image
Pieter van der Westhuizen

Pieter van der Westhuizen is a freelance software and web developer specializing in ASP.NET MVC, web technologies, and MS Office development. He started his career in web development using classic ASP, Visual InterDev, HoTMetaL, and FrontPage. Pieter has over 16 years of experience in the IT industry and is also one of the people fortunate enough to have his hobby become his full-time profession. He is also a technology evangelist for Add-in Express (www.add-in-express.com), which focuses on tools for Microsoft Office integration. This is Pieter's second book and he has been blogging since 2007 on his personal blog at www.mythicalmanmoth.com and on the Add-in Express blog since 2010. He lives with his wife and two dogs in Pretoria, South Africa.
Read more about Pieter van der Westhuizen

Right arrow

Chapter 5.  Creating MVC Bootstrap Helper and Tag Helpers

ASP.NET Core allows developers to create their own HTML Helper methods either by creating static or extension methods. In essence, an HTML Helper is simply a method that returns an HTML string.

HTML Helpers enable you to use the same common block of markup on multiple pages and make the code and markup in your pages easier to read and maintain. This promotes the use of reusable code, and developers can also unit test their helper methods.

ASP.NET Core also introduced a new concept called a Tag Helper that serves a similar purpose to a HTML Helper. The Tag Helpers is not a replacement for the traditional the HTML Helpers but provides developers with an alternative way to generate cleaner HTML markup.

In this chapter, we will cover the following topics:

  • An overview of the built-in ASP.NET Core HTML and Tag Helpers

  • Creating HTML Helpers using static methods

  • Creating HTML Helper using extension methods

  • Creating self-closing helpers

  • Creating...

Built-in HTML Helpers


An HtmlHelper is a method that renders HTML content inside a view. It is intended to allow developers to reuse a common block of HTML markup across multiple pages.

ASP.NET MVC provides a range of standard, out-of-the-box HTML Helpers. For example, to produce the HTML for a textbox with an ID and name attribute of CustomerName, use the following code:

<input type="text" name="CustomerName" id="CustomerName"> 

You should use the TextBox helper as illustrated:

@Html.TextBox("CustomerName") 

The majority of the built-in HTML Helpers offer several overloaded versions. For instance, to create a textbox and explicitly set its name and value attributes, you should use the following overloaded TextBox helper method:

@Html.TextBox("CustomerName"","Northwind Traders") 

Most built-in helpers also offer the option to specify HTML attributes for the element that is generated by passing in an anonymous type. In the following example, we'll create a textbox and set its style property...

Built-in Tag Helpers


Tag Helpers are a new feature that have been introduced with ASP.NET MVC Core; their purpose is similar to those of HTML Helpers, but they provide an alternative syntax to the traditional HTML Helpers. Currently, ASP.NET MVC Core provides a range of built-in Tag Helpers; for example, consider the following HTML for a textbox with an ID and a name attribute of CustomerName:

<input type="text" name="CustomerName" id="CustomerName" class="form-control"> 

To generate the preceding HTML markup using a Tag Helper and data passed in to the view via a model, you would use the following:

<input asp-for="CustomerName" class="form-control" /> 

As you can see, Tag Helpers provide a cleaner syntax and will also make it easier for designers to understand the page markup without having to know any Razor syntax.

Tip

You can learn more about Tag Helpers at http://bit.ly/TagHelpers.

The difference between HTML Helpers and Tag Helpers


Tag Helpers are attached to HTML elements inside your Razor views and can help you write markup that is both cleaner and easier to read than the traditional HTML Helpers. HTML Helpers, on the other hand, are invoked as methods that are mixed with HTML inside your Razor views.

Visual Studio also provides minimum IntelliSense support when writing HTML Helpers, as the parameters for the HTML Helper methods are all strings. For example, in the following code, the LabelFor and TextBoxFor HTML Helper methods are used to create a label and textbox for a model property:

<div class="form-group"> 
    @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" }) 
    <div class="col-md-10"> 
        @Html.TextBoxFor(m => m.Email, new { @class = "form-control" }) 
    </div> 
</div> 

Because the class is a reserved word in C#, you will notice in the preceding code how you have to append the @ sign in order to...

Creating HTML Helpers using static methods


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:

  1. Create a new folder called Helpers inside the root folder of your project.

  2. Add a new class to this folder called Enums.cs. This file will contain all the enumerators for our project.

  3. Add the following code to the Enums.cs file:

            public class Enums 
            { 
                public enum ButtonStyle 
                { 
                    Default, 
                    Primary, 
                    Secondary, 
                    Success, 
                    Info, 
                    Warning, 
                    Danger 
                } 
     
                public enum ButtonSize 
                { 
                    Large, 
                    Small, 
          ...

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...

Creating self-closing helpers


Self-closing helpers are helpers that can contain HTML and Razor markup. The built-in @Html.BeginForm() helper is an example of this helper type.

In order to create this type of HTML Helper, we'll need to create a helper class that implements the IDisposable interface. Using the IDisposable interface, we can write the element's closing tags when the object is disposed.

The Bootstrap Alert component is a good candidate for such a helper. To create the helper, we'll have to complete the following steps:

  1. Create a new subfolder called Alerts inside the Helpers folder in your project.

  2. Open the Enums.cs file and add a new item called AlertStyle:

            public enum AlertStyle 
            { 
                Default, 
                Primary, 
                Success, 
                Info, 
                Warning, 
                Danger 
            } 
    
  3. Add a new class file called Alert.cs to the Alerts folder.

  4. Add a new private, read-only TextWriter object field to the class called _writer:

            private...

Creating a Bootstrap button Tag Helper


Tag Helpers are a new addition to ASP.NET MVC Core and can be used to generate HTML markup. The syntax of Tag Helpers is similar to traditional HTML elements, but is still processed on the server.

Although traditional HTML Helpers are still available, Tag Helpers are intended as an alternative, if not replacement, syntax.

To create your own custom Tag Helper that will generate a Bootstrap button, complete the following steps:

  1. Add a new folder called TagHelpers to your project.

  2. Create a new class called BootstrapButtonTagHelper in the TagHelpers folder.

  3. Change the BootstrapButtonTagHelper to inherit from the TagHelper class, which is a built-in class of the Microsoft.AspNetCore.Razor.TagHelpers package.

  4. In order to use the TagHelper class, add the following to the top of the BootstrapButtonTagHelper class:

            using Microsoft.AspNetCore.Razor.TagHelpers; 
    
  5. Next, add two properties, called Color and Style, to the class. The two properties' data types will...

Creating a Bootstrap Alert Tag Helper


To create a Bootstrap Alert Tag Helper, which will be a little bit more advanced than the previous example, follow these steps:

  1. Create a new class called BootstrapAlertTagHelper in the TagHelpers folder.

  2. Change the class to inherit from TagHelper.

  3. Add a Boolean property called Dismissable and a string property called Color to the class:

             public bool Dismissable { get; set; } 
            public string Color { get; set; } 
    
  4. Next, override the ProcessAsync method, as illustrated here:

            public override async Task ProcessAsync(TagHelperContext context, 
           TagHelperOutput output) 
            { 
                output.TagName = "div"; 
                output.Attributes.Add("class","alert alert-" + Color); 
                output.Attributes.Add("role", "attribute"); 
                if (Dismissable) 
                    output.PostContent.SetHtmlContent( 
                $"<button type="button" class="close" data-dismiss="alert">
                <span aria-hidden="true...

Summary


In this chapter, you explored how you can decrease the amount of markup in your views using HTML Helpers and Tag Helpers. You also learned how to write helpers that will enable developers who are not familiar with the Bootstrap framework to use helpers to add styled components to their views.

In the next chapter, you'll dive into generating scaffolded views that are correctly styled using the Bootstrap 4 styles and layouts.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Bootstrap for ASP.NET MVC - Second Edition
Published in: Sep 2016Publisher: ISBN-13: 9781785889479
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Pieter van der Westhuizen

Pieter van der Westhuizen is a freelance software and web developer specializing in ASP.NET MVC, web technologies, and MS Office development. He started his career in web development using classic ASP, Visual InterDev, HoTMetaL, and FrontPage. Pieter has over 16 years of experience in the IT industry and is also one of the people fortunate enough to have his hobby become his full-time profession. He is also a technology evangelist for Add-in Express (www.add-in-express.com), which focuses on tools for Microsoft Office integration. This is Pieter's second book and he has been blogging since 2007 on his personal blog at www.mythicalmanmoth.com and on the Add-in Express blog since 2010. He lives with his wife and two dogs in Pretoria, South Africa.
Read more about Pieter van der Westhuizen