ASP.NET MVC > Bundles


What are bundles in ASP.NET MVC?

Bundles are a great feature in ASP.NET MVC Framework that provides option to organize and optimize the JavaScript and CSS files that is used in Layout and Views pages.

There are two types of bundles

  1. ScriptBundle that let us organize and optimize JavaScript files
  2. StyleBundle that let us organize and optimize CSS files

Script and Style bundles are defined in ~/App_Start/BundleConfig.cs file and can be used in Layout and View pages.

bundles.Add(new StyleBundle("~/Content/css").Include(

bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(

In order to work with Bundles, we need to use System.Web.Optimization namespace.

In above code snippet, we have defined "~/Content/css bundle that renders bootstrap.css and site.css. The other bundle renders .js file whose name starts with modernizr....

ScriptBundle and StyleBundle can be used in the view like this



The output of above code snippet would look like below in the web page source

In case debug mode is "false" in web.config file  or BundleTable.EnableOptimizations = true; is set in the BundleConfig.cs file

<link href="/Content/css?v=MDbdFKJHBa_ctS5x4He1bMV0_RjRq8jpcIAvPpKiN6U1" rel="stylesheet"/>

    <script src="/bundles/modernizr?v=wBEWDufH_8Md-Pbioxomt90vm6tJN2Pyy9u9zHtWsPo1"></script>

This renders the .optimized css and .js file ie. any comment, alignment  in the .css and .js file is removed to make the file size less so it loads quickly. As the StyleBundle has added two .css file so both file will be merged into one and loaded into browser to redule the number of requests on the server to load both files. This intern helps to increase the performance of the web page.

In case debug mode is false

<link href="/Content/bootstrap.css" rel="stylesheet"/>
<link href="/Content/site.css" rel="stylesheet"/>

    <script src="/Scripts/modernizr-2.6.2.js"></script>

Notice that first StyleBundle adds two css file separated by "comma" so it has rendered two .cssf file.

 Views: 2051 | Post Order: 115

Write for us