Posted by on Feb 20, 2012 2:02 AM in asp,mvc,4 | 0 comments

There are some very awesome features that came with the release of ASP.NET MVC 4. Here is a list of them and some samples on how to use them.

Razor now supports the ~ semantic

How many of you are tired of seeing the following bit of ugly code?

<link href="@Url.Content("~/Content/css/style.css")" rel="stylesheet" type="text/css" />

With the new feature, you can now write (a little less fluff)

<link href="~/Content/css/style.css" rel="stylesheet" type="text/css" />

Minification and Bundling

This is a feature that I am sure a lot of developers will absolutely love.

Bundling is the ability to bundle a set of files. The less requests to the server, the better. For example, let's assume you are using twitter's bootstrap and your own set of custom styles in a separate file but they are both inside of a folder called "/Content". By using the BundleUrl method from the System.Web.Optimization namespace, it will bundle the css up into a single css and serve that to the client's browser. However, there are 2 ways that you accomplish this and the one does offer something above the other.

the first way uses a convention based approach

<link href="/Content/css" rel="stylesheet" />

the second uses the ResolveBundleUrl which caches the minified file on the client for a year by using a hash to check if the file has changed, otherwise it will not even request the file.

<link href="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Content/css")" rel="stylesheet" type="text/css" />

Here is a comparison between the 2 as served to the client

alt text

Custom Rules With the bundling comes, custom bundling, the ability to create our own bundles by using the Bundle class and registering that in the BundleTable and after that being able to reference your custom bundle name in the application.

var bundle = new Bundle("~/YourScripts", typeof([JsMinify][6]));
bundle.AddDirectory("~/someScripts", "*.js", true); //include sub folders
BundleTable.Bundles.Add(bundle);

Custom Processing Let's assume that you also want to implement something like CoffeeScript or Less that requires different kind of processing, the team has also given us the ability to provide that functionality by using DynamicFolderBundle

i.e.

var coffeeScript = new DynamicFolderBundle("coffee", typeof(CoffeeTransform), "*.coffee");
BundleTable.Bundles.Add(coffeeScript);
BundleTable.Enabled = true;

More resources :

Scott Guthrie's post on the ASP.NET MVC 4 Beta

Bundling and Minification Exercise on MSDN

In the coming weeks, I will dig a more into this, but for now, Start New Project your way into ASP.NET MVC 4 Beta (which comes with a golive license)

Read More