Another benefit of MVC bundling package is when you release an update to a CSS file the client will get the latest changes rather than the cached version. Because the file has an appended query string with a hashed version which is automatically updated with the file is changed. You don’t even need to rebuild or build the web project after its running.
Bundling in MVC 4
This is pretty easy to set up. If you start a new project then this is already preconfigured and is set up using the default CSS and JS files. If you want to add in your own files or alter the file structure you will need to change your code slightly in the global.asax.cs file. If you change the file structure the method RegisterTemplateBundles will return nothing or not include your new files. This is because the files are registered, meaning it looks for those specific files. What you need to do is change this to EnableDefaultBundles in the global.asax.cs file, inside the Application_Start method. See example below: Change from this:
If you have upgraded your project from MVC 3 to MVC 4 then all you need to do is add the following lines of code to your _layout.cshtml file in between the head element.
Can I bundle using MVC 3?
You can indeed. It is of course slightly more involved. In your project go to Nuget project manager and search for microsoft.web.optimization and make sure you include pre-releases in the drop down. You will need to install the latest beta version. Once that is installed add the using to the global.asax.cs file and add the following method as well.
An important thing to note is in debug mode the scripts and css files are referenced normally, not bundled and minified. When you create your deployment package or release package the files are bundled together. But you can check if they are bundling the way you expect by adding in this line in your new RegisterBundle function.
Now you can check nothing strange happens when putting the files together. Obviously it is important that certain scripts are loaded in the correct order as they might have dependencies on each other.
How to reference your new bundle in the _layout.
By using the following lines for outputting the markup for referencing style and script files between the head tag.
There you have it, how to bundle your styles and scripts in both MVC 4 and 3 to help improve the performance of your web sites.