Bundle in ASP.NET MVC

| By Webner

Bundle in ASP.NET MVC

Bundling is a process that allows us to load a bunch of static files from the server into one HTTP request. We can load multiple CSS and Javascript files using bundles.

Let’s take an example :

In the above example browser sends two separate requests for loading two different JS files.

Bundling allows us to do that in one request.

In MVC 5 bundle classes are included in System.web.Optimization namespace:

Open App_Start\BundleConfig.cs file in the MVC folders. The BundleConfig.cs file is created by MVC framework by default. You should write your all bundling code in the BundleConfig.RegisterBundles() method.


Minification optimizes script or CSS file size by removing unnecessary comments and white space and shortening variable names to one character.

Example: JavaScript

check = function(name){
 //it is comment
 var msg = "Check" + age; 

The above JavaScript will be optimized and minimized into the following script.

check =function(n){var t="Check"+n;alert(t)}

Minification removes unnecessary white space, comments and also shortening variable names to reduce the characters which in turn will reduce the size of the JavaScript file.

Bundling and minification impacts the loading of the page, it loads the page faster by minimizing the size of the file and number of requests.

Bundle Types

ScriptBundle:It is responsible JavaScript minification of single or multiple script files.

public static void RegisterBundles(BundleCollection bundles) { 
// create an object of ScriptBundle and
 // specify name of bundle (as virtual path) as constructor parameter 
ScriptBundle scB = new ScriptBundle("~/bundles/bootstrap");
 //use Include() method to add all the script files along with their paths 
scB.Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js" ); 
//Add it bundle into BundleCollection 
BundleTable.EnableOptimizations = true; 

StyleBundle: It is responsible for CSS minification of single or multiple style sheet files.

public static void RegisterBundles(BundleCollection bundles) { 
bundles.Add(new StyleBundle("~/bundles/css").Include( "~/Content/bootstrap.css",          
                                                                                         "~/Content/site.css" )); 


Include the bundles in razor view

For StyleBundle:

For ScriptBundle:

Leave a Reply

Your email address will not be published. Required fields are marked *