Setting Up Bundler in ASP.Net MVC

Mar 28, 2014 • val antonini

Bundling CSS files

Install the Microsoft.AspNet.Web.Optimization nuget package:

Install-Package Microsoft.AspNet.Web.Optimization

Add a BundleConfig.cs in AppStart:

using System.Web.Optimization;

namespace SampleApp.Web.App_Start
{
    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new StyleBundle("~/Styles/Site") //Make sure this doesn't resolve to a directory on the server
                .Include("~/Content/Site.css") //Add the CSS files you want bundled
            );
        }
    }
}

Edit the global.asax.cs to use the bundle config above:

BundleConfig.RegisterBundles(BundleTable.Bundles);

Render the style bundle in the _Layout or View:

@Styles.Render("~/Styles/Site")

Bundling Javascript files

The same can be applied to Javascript files.

Register the bundle in the BundleConfig.cs as below:

bundles.Add(new ScriptBundle("~/Scripts/Site") //make sure this doesn't resolve to a directory on the server
       .Include("~/Scripts/Site.js"));

Add to the view below:

@Scripts.Render("~/Scripts/Site")