Follow by Email

Friday, December 5, 2014

Implementing bundling in asp.net mvc application || optimization of asp.net mvc application

hi here we will see how to implement bundling in asp.net mvc 4.
Bundling helps us to reduce the number of http requests made for calling .css and .js files. Bundling is a process where we bind multiple js or css files into one , so that we can reduce the number of http requests made for calling this files and thus improving the performance of a web application.

1. create a new mvc project, and go to manage nuget packages options and install asp.net web optimization framework.
11

2. now go to solution explorer app_start folder and create a new class called BundleConfig.cs
55

3. in bundleConfig.cs create seperate bundles for js and css files.
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new Bundle(“~/bundles/mycss”).Include(“~/css/StyleSheet1.css”,”~/css/StyleSheet2.css”));
bundles.Add(new ScriptBundle(“~/bundles/jsbundle”)
.Include(“~/js/jquery-2.1.1.js”).Include(“~/js/JavaScript1.js”));
//another way
//var bootstrapCss = new Bundle(“~/bootstrap/css”, new CssMinify());
//bootstrapCss.Include(“~/css/StyleSheet1.css”);
//bootstrapCss.Include(“~/css/StyleSheet2.css”);
//bundles.Add(bootstrapCss);
//var bootstrapJs = new Bundle(“~/bootstrap/js”, new JsMinify());
//bootstrapJs.Include(“~/js/jquery-2.1.1.js”);
//bootstrapJs.Include(“~/js/JavaScript1.js”);
//bundles.Add(bootstrapJs);
}
}
4. Now go to global.asax.cs file and add
BundleConfig.RegisterBundles(BundleTable.Bundles);
BundleTable.EnableOptimizations = true;
44

5. a) make sure debug is set to false in the web.config file of the application
b) and under <system.web> <pages><namespaces> tag add
  <add namespace=”System.Web.Optimization”/>
6. now we will go to view page(.cshtml) and add the js and css bundle references
66
@using System.Web.Optimization;
<!DOCTYPE html>
<html>
<head>
<meta name=”viewport” content=”width=device-width” />
@Styles.Render(“~/bundles/mycss”)
@Scripts.Render(“~/bundles/jsbundle”)
<title>Samplepage</title>
</head>
<body>
<div>
<h1>Hi welcome to my site</h1>
<p>Enter your Name:</p>
<input id=”txtName” type=”text”/>
<button onclick=”message();”>Enter</button>
</div>
</body>
</html>

now lets run the application to check
output:
1. Before Bundling
22
2. After Bundling ( Check the time )
77