Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Bootstrap for ASP.NET MVC - Second Edition

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

Product type Book
Published in Sep 2016
Publisher
ISBN-13 9781785889479
Pages 186 pages
Edition 2nd Edition
Languages
Author (1):
Pieter van der Westhuizen Pieter van der Westhuizen
Profile icon Pieter van der Westhuizen

Table of Contents (15) Chapters

Bootstrap for ASP.NET MVC Second Edition
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
1. Getting Started with ASP.NET Core and Bootstrap 4 2. Using Bootstrap CSS and HTML Elements 3. Using Bootstrap Components 4. Using Bootstrap JavaScript Components 5. Creating MVC Bootstrap Helper and Tag Helpers 6. Converting a Bootstrap HTML Template into a Usable ASP.NET MVC Project 7. Using the jQuery DataTables Plugin with Bootstrap 4 8. Creating Bootstrap 4 ASP.NET MVC Sites Using Visual Studio Code Bootstrap Resources

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 2016 Publisher: 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.
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 €14.99/month. Cancel anytime}