Alexander Beletsky's development blog

My profession is engineering

New in ASP.NET MVC4: Razor changes

Razor has been changed a little with ASP.NET MVC 4 beta. It’s not a kind of radical changes, but rather improvements that make developers happier. As for me, developers happier then you need to write less code to get the same function. It reminded me a ideal device, which is part of TRIZ theory. Ideal device is a device that does not exit, but does it function. By analogy, ideal code is the code that not exist but it’s function exist. Razor is not that ideal, through.. But it’s “more ideal” than previous version.

No more @Url.Content

I got used to @Url.Content and used that for all CSS and JS references. Since it’s to commonly used, developers decided to include it on a level of engine. Now, instead of

<script src="@Url.Content("~/Scripts/Controls.js")"></script>

You simply can write,

<script src="~/Scripts/Controls.js"></script>

If Razor detects ~/ it would created an output identical to @Url.Content. Just got rid of several bytes within view files.

Conditions

Conditions in attributes were pretty noisy. Have you ever create something like this?

<div @{if (myClass != null) { <text>class="@myClass"</text> } }>Content</div>

I had and I did not like it much. I usually ended up with creation of some simple HTML helper instead. With new Razor it a little simpler, not you can write

<div class="@myClass">Content</div>

If @myClass is null, it won’t output class attribute at all. Very handy.

And a little more

This is an update section I created after this post has been twitted by Scott Guthrie and some valuable comments has been received.

Brad Wilson stated, conditions does not only support nullable types, but also booleans. Say, I have code:

<input checked="@ViewBag.Checked" type="checkbox"/>

If the @ViewBag.Checked in null or false, it will be rendered as:

<input type="checkbox"/>

Else if @ViewBag.Checked is true, it will be rendered as:

<input checked="checked" type="checkbox"/>

Erik Porter also mentioned the custom support for data-* attributes. Data attributes are little special, so even if you missing particular value you still want to have those as empty data-role = "". So, if you have code like:

<ul data-role="@ViewBag.ListRole">
</ul>

and @ViewBag.ListRole is null or false, data attribute will be eliminated. That’s how it work in Beta. But for next releases data-* attributes will be treated specially, so even if value is null or false they will be rendered as empty ones.

Conclusions

I haven’t noticed any more changes so far. It’s great to see that Razor has not been “frozen” and still improving. I like that view engine first of all by it’s simplicity. So making it even more simple would definitely make it more attractive.