New features of ASP.NET MVC 4 that you will love

by Leon Cullens 27. februari 2012 22:52

I recently saw Scott Guthrie's presentation of ASP.NET MVC 4 on the TechDays in the Netherlands. How showed us a couple of very interesting features that are new to ASP.NET MVC 4. Here are the coolest features that you will definitely love.

Not only MVC

First of all I want to make clear that most features aren't MVC-specific features. However, MVC does implement most of them out-of-the-box, while Web Forms needs some more installation and configuration work.

Front-end

Minification

There are some really neat features on the front-end part of MVC 4, first of all there's minification. Minification means that all spaces, enters and comments are removed from your CSS / Javascript files (including coffee, SASS and LESS), and that variable names are replaced with shorter variable names (such as a, b, c, etc.). This means that less data needs to be transferred to the visitors of your website, resulting in a faster page loading time, etc. Probably a feature that any front-end developer will love.

Bundling

Another cool feature that is often mentioned in one sentence with minification is bundling. Bundling means that you can have separate CSS files (e.g. one for your content, one reset style sheet, one for your layout) that are 'bundled' into one CSS file. ASP.NET does this by convention (but it's also configurable), for example: the reset.css will be placed in the bundle first, etc. This means that you only have one request instead of multiple requests, again resulting in a faster page load time.

Mobile web

Much has been done to improve the way MVC 4 behaves on mobile devices. There's now a mobile application project type that creates a nice lay-out that uses JQuery mobile to do all kinds of fancy stuff. MVC 4 also tries to render your lay-out in a mobile compatible way. This means that your elements are properly resized to fit inside the screen of mobile devices. But this is not the only feature, nor is it the most exiting feature. The most important mobile web feature (in my opinion) is the fact that you can now create device specific views. This allows you to create specific views for Windows Phone 7 devices, for Android devices, etc.

Project templates

For those who just want to make a quick prototype there are new project templates that look pretty fancy compared to the old project templates. Below is an overview of the new templates, the left template is the default template when you choose the 'internet application' project type, the second is the 'single page application' type and the third, obviously, the mobile type. The new project types also support AJAX login and OAuth.

MVC4 default template

MVC4 single page template

MVC4 mobile template

Back-end

Web APIs

A very exiting new feature of ASP.NET is the introduction of Web APIs. This is another name for the new controller type, namely the ApiController. The ApiController makes creating an API much easier compared to WCF. Just like the default MVC controllers you can mark methods to be HttpPost methods, HttpGet methods, etc., but there are many new features to this.

The ApiController now allows users to perform queries against the API with OData if the ApiController method returns IQueryable<T>, it's possible to return specific HTTP codes to the consumer of the API, there's improved testability and IoC support, and more features that you will love.

Since the ASP.NET team and the WCF team have been merged, the new ASP.NET Web API wil replace some parts of WCF. This is a good things because the Web API is really easy (and flexible) to work with.

If you want to know more about ASP.NET's Web API I recommend Scott Guthrie's blog post about it.

Async

There was Async support in MVC 3. This meant that you need to have two methods: an Async method and a Completed method. MVC 4 removes the need for two methods and simplifies the way tasks are defined. Below are two examples:

The MVC 3 approach:

public void IndexAsync(string city) {
    AsyncManager.OutstandingOperations.Increment(2);

    NewsService newsService = new NewsService();
    newsService.GetHeadlinesCompleted += (sender, e) =>
    {
        AsyncManager.Parameters["headlines"] = e.Value;
        AsyncManager.OutstandingOperations.Decrement();
    };
    newsService.GetHeadlinesAsync();

    SportsService sportsService = new SportsService();
    sportsService.GetScoresCompleted += (sender, e) =>
    {
        AsyncManager.Parameters["scores"] = e.Value;
        AsyncManager.OutstandingOperations.Decrement();
    };
    sportsService.GetScoresAsync();
}

public ActionResult IndexCompleted(string[] headlines, string[] scores, string[] forecast) {
    return View("Common", new PortalViewModel  {
        NewsHeadlines = headlines,
        SportsScores = scores,
    });
}

The MVC 4 approach:

public async Task<ActionResult> Index(string city) {
    var newsService = new NewsService();
    var sportsService = new SportsService();
    
    return View("Common",
        new PortalViewModel {
        NewsHeadlines = await newsService.GetHeadlinesAsync(),
        SportsScores = await sportsService.GetScoresAsync()
    });
}

(Source: ASP.NET on CodePlex)

As you can see the MVC 4 approach is much shorter and much easier, probably leading to more people using asynchronous methods. The code is still compiled into the same intermediate language, it's just syntactic sugar.

Real-time communication

There's also support for WebSockets and a new open source framework called SignalR that allows you to set up a real-time multi-user interactive website in a real easy manner. I highly recommend reading Scott Hanselman's blog post about SignalR and the official SignalR Github project.

Database migrations

The last feature that I wanted to mention is probably the coolest new feature. However, it's rather an Entity Framework feature than an ASP.NET feature. I'm talking about Entity Framework 4.3's new Database Migrations.

What it means is that Entity Framework can generate classes with Execute/Unexecute (actually they are called Up and Down, but I don't think those names really describe what they do), performing any database modifications that you've made. For example: let's say we have an entity called Person. If I wanted to add a property called 'Age' to Person entity, Entity Framework would generate a class for me with two methods: the Up method that adds the Age property to the Person table in the database (or whatever we've mapped the Person entity to) and the Down method that removes the Age property from the Person table. This allows us to rollback any changes, or easily perform updates on the database.

Entity Framework also allows us to generate SQL so we don't have to write change scripts manually any more. Automating the generation of change scripts can significantly reduce the time it takes to deploy your application, allowing the developers to focus on developing new features.

I recommend Scott Hanselman's post about it and this walkthrough if you want to start working with it right away.

Conclusion

With MVC version 4 the ASP.NET MVC framework will finally get the front-end developer's seal of approval by introducing some really neat features that any modern website needs, no excuses. The addition of support for useful frameworks such as SASS and LESS show that Microsoft is finally taking front-end development a bit more serious. With the new Web API we will probably see the death of WCF, making the choice for an API framework a bit easier (WCF had way too many different project types in my opinion). The Web API has lots of very cool features that will make creating an API much easier. The new Async features and Entity Framework's Database Migration feature will be saving back-end developers a lot of time and frustration as well.

If you want to see Scott Guthrie's presentation about MVC 4, DB Migrations and SignalR, you can view it here on Channel9 (I highly recommend doing so if you have nothing to do).

Tags: , , , , , , , , ,

ASP.NET MVC

Comments (10) -

Andy
Andy United Kingdom
29-2-2012 14:16:49 #

Does System.Web.Optimization include minify of property names? I've not used it yet, but had thought it only removed whitespace.

Reply

Leon Cullens
Leon Cullens Netherlands
29-2-2012 15:33:22 #

I can't find it on MSDN, but as far as I know this does happen. But it's still beta anyway, so a lot of things will change in the coming months.

Reply

iON
iON United States
29-2-2012 23:07:02 #

Regarding the Real-time communication section;

SignalR is not a Microsoft product! It has been developed as a side project by employees of Microsoft and that is the extent of the affiliation.

There is also no relationship between MVC 4 and SignalR as SignalR does NOT require MVC to function. SignalR can be self hosted, run in IIS/ASP.NET or run in anyone of the alternative web servers that support the OWin (Open Windows Interface for .Net) standard (Kayak etc).

WebSockets support will only be in the Windows 8/.Net 4.5 platform unless there is a custom (Non MS) implementation ... it is not part of MVC 4. SignalR falls back to the Sever-Sent Events, Forever Frame or Long Polling transports if WebSocket support  (Platform or custom) is not available.

More homework needs to be done to make this section factual.

Reply

Leon Cullens
Leon Cullens Netherlands
29-2-2012 23:16:33 #

Thanks for the clarification!

Reply

Pedro Sousa
Pedro Sousa Portugal
1-3-2012 2:09:43 #

This is a good thing, because the ApiController works much easier than any WCF service I've seen so far, and it supports pretty much all the features that WCF supports.

Not to be offensive, but can I have one of those things that you're smoking? Smile

The Web API is pretty cool but it just "replaces" a little part of the WCF stack.

Reply

tec-goblin
tec-goblin Greece
6-3-2012 22:58:00 #

I agree, WCF is huge. Saying that the Web API will replace WCF equals to saying that WS-Reliability, WS-Addressing, WS-Transactions and all the other advanced web service and soap interoperability stuff do not exist.
Web API can only replace a part of WCF Data Services (the RESTful part of WCF)

Reply

executive coaching sydney
executive coaching sydney Australia
1-3-2012 6:32:08 #

Web optimization is must for any online website, Its really great if asp include new features for it.

Reply

gaston
gaston Belgium
6-3-2012 11:24:21 #

Nice wrap up of all the features! It's also very nice to have all the links together on 1 page. Bookmarked Smile

Reply

jlafay
jlafay United States
7-3-2012 17:04:38 #

How does Web API compare to other REST frameworks available such as Service Stack? The description sounds remarkably similar.

Reply

Umarali
Umarali India
24-9-2012 14:42:46 #

Really nice to see ASP.NET MVC 4  features in a nutshell .Thanks!

Reply

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

about

Name: Leon Cullens
Country: The Netherlands
Job: Software Engineer / Entrepreneur
Studied: Computer Science 
Main skills: Microsoft technology (Azure, ASP.NET MVC, Windows 8, C#, SQL Server, Entity Framework), software architecture (enterprise architecture, design patterns), Marketing, growth hacking, entrepreneurship

advertisements

my apps