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.