To keep it simple I'm going to go through taking a "vanilla" MVC 3 app and enhancing it to work with Web Optimization. To start, follow these basic steps:
- Open Visual Studio (bet you didn't see that coming!)
- Create a new MVC 3 application (I called mine "WebOptimizationWithMvc3" to demonstrate my imaginative flair). It doesn't really matter which sort of MVC 3 project you create - I chose an Intranet application but really that's by the by.
- Update pre-existing NuGet packages
- At the NuGet console type: "
Whilst the NuGet package adds the necessary references to your MVC 3 project it doesn't add the corresponding namespaces to the web.configs. To fix this manually add the following child XML element to the
<namespaces> element in your root and Views web.config files:
<add namespace="System.Web.Optimization" />
This gives you access to
Styles in your views without needing the fully qualified namespace. For reasons best known to Microsoft I had to close down and restart Visual Studio before intellisense started working. You may need to do likewise.
BundleConfig.cs which looks like this:
BundleConfig.cs you should modify your
Global.asax.cs so it looks like this:
Once you've done this you're ready to start using Web Optimization in your MVC 3 application.
_Layout.cshtml. To switch over to using Web Optimization you should replace the existing
_Layout.cshtml with this: (you'll see that the few differences that there are between the 2 are solely around the replacement of link / script tags with references to
Do note that in the above
Scripts.Render call we're rendering out 3 bundles; jQuery, jQuery UI and jQuery Validate. We're not using any of these in
_Layout.cshtml but rendering these (and their associated link tags) gives us a chance to demonstrate that everything is working as expected.
In your root web.config file make sure that the following tag is in place:
<compilation debug="<b>true</b>" targetFramework="4.0">. Then run, the generated HTML should look something like this:
This demonstrates that when the application has debug set to true you see the full scripts / links being rendered out as you would hope (to make your debugging less painful).
Now go back to your root
web.config file and chance the debug tag to false:
<compilation debug="<b>false</b>" targetFramework="4.0">. This time when you run, the generated HTML should look something like this:
This time you can see that in non-debug mode (ie how it would run in Production) minified bundles of scripts and css files are being served up instead of the raw files. And that's it; done.