Thursday 17 July 2014

Bundling in Asp.Net

Install necessary Dlls using Package Manager console.

PM> Install-Package Microsoft.AspNet.Web.Optimization

Now add a class file and copy below code in it : 

using System.Web.Optimization;
public class Bundle

        public void AddBundle()
var JSBundle = new ScriptBundle("~/JSfiles");
            // JSBundle.Include("~/   Path of your file with ext.");

            var styleBundle = new StyleBundle("~/Style");
            // styleBundle.Include("~/   Path of your file with ext.");
            BundleTable.Bundles.Add(styleBundle);        }

Register your bundle in Application_Start event in Global.asax : 

protected void Application_Start(object sender, EventArgs e)
      Bundle bndle = new Bundle();

Now Take .aspx page in which you want to render your bundled css or JS files.

<%@ Page Language="C#" AutoEventWireup="true"
   CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>

<!DOCTYPE html >

<html xmlns="">
<head runat="server">

 <%:  System.Web.Optimization.Scripts.Render("~/JSfiles") %>
 <%: System.Web.Optimization.Styles.Render("~/Style") %>

        $(document).ready(function () {
    <form id="form1" runat="server">

 Now in Web.config. If you want to enable bundling for your application then you have to make debug = false.

    <compilation debug="false" targetFramework="4.5"/>


Now check if your bundling is working or Not ?

Press F12 in IE.  Then Script Tab and check in drop-down in right side. You will have name of the JS file which you have given in application. if you click on that you will find minified JS of all JS. You will not found actual path of your JS. see Page Source


No comments:

Post a Comment