Razor 2: URL resolution improvements

Until now, it was common to see this pattern in our views:

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

The Content method is a helper method which is responsible for converting a relative path into an absolute path. From now on (where now is the MVC4 release date which happened sometime ago Smile), we can simplify our code so that it looks like this:

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

Yes, we no longer need to resort to the helper because Razor is smart enough to translate all attribute’s values that start with ~/ into a   @Url.Content call. And when I say *all*, I do mean all. For instance, if the parser finds this:

<div data-info="~/info.txt">Some info</div>

It’s as if you had written this:

<div data-info="@Url.Content("~/info.txt")">Some info</div>

Notice you can also mix values with other code snippets. For instance, suppose you need to build an URL that combines an URL with some variable aux. In that case, you can simply write something like this:

<script src="~/scripts/@aux"></script>

The previous snippet will get translated into the following:

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

Simple, but nice, right? Razor 2 introduces a couple of other interesting features (ex.: conditional attributes), but we’ll leave that for a future post. Stay tuned for more.


~ by Luis Abreu on September 22, 2012.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: