ASP.NET MVC 4 Razor v2 - New Features


With the imminent release of ASP.NET MVC 4 my previous post ASP.NET MVC 3 Razor - The Ultimate Quick Reference needed a follow-up on what's new in the view-engine Razor v2, that comes with MVC 4.

App-relative URLs automatically resolved

In Razor v1 your views would be littered with code like this:

<script src="@Url.Content("~/content/scripts.js")"></script>

But in Razor v2 you can shorten it with a tilde in front of the URL, which was used a lot in WebForms:

<script src="~/content/scripts.js"></script>

This will work for any HTML-attribute that starts with the title-sign.

Conditional attributes hides null-valued attributes

Razor v1 treated null-valued attributes as empty string, writing out attributes empty values. Razor v2 will instead skip even writing out the attribute that has a null value:

    string itemId = string.Empty;
    string itemClass = "class-of-item";
    string itemValue = null;
<div id="@itemId" class="@itemClass @itemValue" rel="@itemValue"></div>

Will result in this HTML:

<div id="" class="class-of-item"></div>

Note that string.Empty still makes Razor v2 to write out the attribute. Any data-attribute will ignore this rule and always write out the attribute.

Support for unclosed HTML-tags

The HTML5-specs clearly states that unclosed HTML-tags are supported, but Razor v1 didn't have an advanced enough parser to support this. Razor v2 now supports this with the elements listed in W3C's spec.

What else?

There has been some major improvements on how the syntax-trees are structured and other deep functionality in the language. The focus was internal clean-up and future-proofing.

DevSum Scheduler - Plan Your Attendance

DevSum 2012

Since I'm attending DevSum 2012 at the end of this month, I felt I needed to keep track of which talks to attend... but also the need to play around with some web-technologies.

From those needs I took some evening hours to build DevSum Scheduler. It's a web-app that allows you to highlight which talks you're going to attend.

The app uses HTML Agility Pack to get the data from DevSum's own website and then ASP.NET MVC Razor to display the content properly. To store this I've used HTML 5 LocalStorage to persist the choices made.

There are many other technologies used, which are listed on the about-page. Since the website is suppose to help the attendees by being available on their smart-phones, I've used CSS Media Queries for mobile layout and Modernizr for feature-detection in the web-browser.

Check out the full source-code on GitHub. Again, the outstanding AppHarbour has been used to quickly get the app on the Internet (through a GitHub-service hook of course).