Book Image

Bootstrap for ASP.NET MVC

By : Pieter van der Westhuizen
Book Image

Bootstrap for ASP.NET MVC

By: Pieter van der Westhuizen

Overview of this book

<p>Bootstrap, a leading open source frontend framework, takes care of typography, form layouts, and user interface components, allowing a developer to focus on writing code. Integrating ASP.NET's powerful components can further enhance its capabilities. This book guides you through the process of creating an ASP.NET MVC website from scratch using Bootstrap.</p> <p>You will learn about various Bootstrap components as well as techniques to include them in your own projects. The book includes practical examples to show you how to use open source plugins with Bootstrap and ASP.NET MVC and will guide you through building a website using Bootstrap, utilizing layout and user interface components. In the process, you will also learn to build HTML helpers and T4 templates as well as how to use the jQuery DataTables plugin. At the end of this book, you will find some valuable tips and tricks, which will help you in getting the most out of your Bootstrap and ASP.NET MVC integrated website.</p>
Table of Contents (18 chapters)
Bootstrap for ASP.NET MVC
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Improving your site performance with bundling and minification


Bundling and minification is a feature in ASP.NET that allows you to increase the speed at which your site loads. This is accomplished by limiting the number of requests to CSS and JavaScript files your site needs to make by combining these types of files into one large file and removing all unnecessary characters, such as comments, white spaces, and new line characters from the files.

Note

Most modern browsers have a limit of six concurrent connections per hostname. This means that if you reference more than six CSS or JavaScript files on a page, the browser will only download six files at a time and queue the rest. Limiting the number of CSS and JavaScript files is always a good idea.

Adding bundling to your Bootstrap project

Because we created an empty ASP.NET MVC site, the necessary reference for adding bundling was not automatically added to our project. Luckily, this can easily be added by using the NuGet Package Manager Console as follows:

  1. Open the Package Manager Console window and enter the following command:

    install-package Microsoft.AspNet.Web.Optimization
    
  2. This will install the Microsoft.AspNet.Web.Optimization NuGet package as well as all the packages it has dependencies on. These dependencies are as follows:

    • Microsoft.Web.Infrastructure

    • WebGrease

    • Antlr

    • Newtonsoft.Json

  3. After the NuGet packages have been installed successfully, create a new static class called BundleConfig inside the App_Start folder.

  4. Inside this class, we'll create a new static method called RegisterBundles, which accepts a parameter called bundles, whose type is a BundleCollection object. The code for the class is as follows:

    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bootstrap/js").Include(
                      "~/js/bootstrap.js",
                      "~/js/site.js"));
    
            bundles.Add(new StyleBundle("~/bootstrap/css").Include(
                      "~/css/bootstrap.css",
                      "~/css/site.css"));
        }
    }

    Bundles come in the following two types:

    • ScriptBundle

    • StyleBundle

    The StyleBundle object is used to add style sheets to a bundle and the ScriptBundle object is used to add JavaScript files. The Add method of the BundleCollection object accepts both types of objects. The StyleBundle and ScriptBundle objects accept a string parameter, which specifies the virtual path of the files, and you should therefore, use the Include method to specify the path to the files you would like to include in the bundle.

Tip

Never include files with .min in their names, for example, bootstrap.min.css or bootstrap.min.js in bundles. The compiler will ignore these files as they are already minified.

Including bundles in your ASP.NET layout

To include the bundles we created earlier in our Layout file, perform the following steps:

  1. Open the _Layout.cshtml file in the Shared folder and change its markup to reflect the following (changes are highlighted):

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>@ViewBag.Title</title>
        @Styles.Render("~/bootstrap/css")
    
        <!--[if lt IE 9]>
          <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
          <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
        <![endif]-->
    </head>
    <body>
        @RenderBody()
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        @Scripts.Render("~/bootstrap/js")
    </body>
  2. If the Visual Studio HTML editor indicates that it cannot find the Scripts or Styles objects (that is indicated by the words being highlighted), this means a reference is missing from the Web.config file inside the Views folder.

  3. To fix this, add a reference to System.Web.Optimization to the list of namespaces in this Web.config file. Consider the following example:

    <namespaces>
      <add namespace="System.Web.Mvc" />
      <add namespace="System.Web.Mvc.Ajax" />
      <add namespace="System.Web.Mvc.Html" />
      <add namespace="System.Web.Routing" />
      <add namespace="AdventureBootstrap" />
      <add namespace="System.Web.Optimization" />
    </namespaces>

Testing bundling and minification

In order to enable bundling and minification, open the Web.config file inside the root of your project and change the debug attribute of the compilation element to true as follows:

<system.web>
  <compilation debug="true" targetFramework="4.5" />
  <httpRuntime targetFramework="4.5" />
</system.web>

The same can be achieved by setting the EnableOptimizations property of the BundleTable object to true. This statement can either be added to the Global.asax file's Application_Start method or to the RegisterBundles method of the BundleConfig class as follows:

BundleTable.EnableOptimizations = true;

After you've added references to the bundles inside your Layout file and set either the debug attribute or the EnableOptimizations property to true, build and run your project. Once the site is open in a browser, view its source. You should see a markup similar to the following:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Index</title>
    <link href="/bootstrap/css?v=Tmmo-oSKW9MFWr7qyt2LfyMD1tap2GokH7z1W2bhfgY1" rel="stylesheet"/>
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body>  
<h2>Index</h2>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="/bootstrap/js?v=raqa-So7giLQpXYq5LQiW8D-yNoxOAJewB8VXtgFHfE1"></script>
</body>
</html>

Note that the highlighted lines contain the relative paths we've specified in our bundles and when clicking on, for example, the /bootstrap/js link, the browser will open a minified version of the Bootstrap JavaScript file. You can see it is minified because most white spaces and line breaks have been removed. The code will also be a combination of the Bootstrap JavaScript file as well as any other JavaScript files, which we might have added to the bundle.