Online Training for Asp.net MVC Web Designing Development, MS SQL, Digital Marketing

Bundling In ASP.NET MVC StyleBundle, ScriptBundle

In this article you learn about Bundling In ASP.NET MVC, StyleBundle, ScriptBundle, BundleConfig.cs, how bundling technique works in ASP.NET MVC.

What is Bundling in Asp.Net MVC?

Bundling is very useful features in Asp.net MVC, here you learn how to create a bundle of multiple JavaScript files or CSS files in one http request.
This is also known as minification of javascript file or css files

How to add files in BundleConfig

Open your Asp.net MVC application, go to App_Start folder, there you see BundleConfig.cs, is created by MVC framework by default
There you see two type of bundle class, StyleBundle and ScriptBundle, Now you can create as many instance as you need of any of those classes and the finally add to BundleCollection. remember BundleCollection class will reamin always one only.
There you see many javascript and css files are already added by default, but you can keep on adding your files this way

BundleConfig.RegisterBundle()

public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
//this is an example of adding css file
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/your_style.css"));

//this is an example of adding javascript file
bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/scripts/your-javascript.js"));

}
}

You can create a new bundle and add files into that or you can include file in existing bundle , notice in above two example we have included file into existing bundle

Sometimes you may need to add third party script where the version of script may change in future, in such case you don't have to specify a version number of a script file, take a look at the example below where we are adding Jquery files .
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery")
.Include( "~/Scripts/jquery-{version}.js"));
}
}

So, in future if Jquery version number change in your project, this will automatically pickup and bundle the file.
RegisterBundles in Application_Start
This how your bundling get executed when application start
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}

Comment
Name Email Website
Subscribe

 
Bundling In ASP.NET MVC
StyleBundle, ScriptBundle, BundleConfig.cs

Group Training