IronShay

Ironing code, geek t-shirts and even presentations!

NAVIGATION - SEARCH

The Razor View Engine Basics

If you’ve been following me, you probably noticed that I became quite excited with the new view engine of ASP.NET MVC 3 – the razor view engine. If you’re familiar with it then you might agree or disagree with me, but if you don’t then this is a great time for you to make up your mind!

In this post I assume you are familiar with the concept of view engines. If not, please watch this before.

Let’s start.

At Sign (@) Galore

The razor view engine is all about the at sign (@). Unlike the inelegant <% %> signs of the common web forms view engine, here all you need is the at sign.
Basically, starting an expression with the at sign will lead to this expression being evaluated and output the result to the page. For example:

@DateTime.Now

This expression will end up printing the current date and time to the response stream. It is the equivalent of the following web forms view engine code:

<%: DateTime.Now %>
Note
At sign expressions are html encoded!
If you’re sure your output is OK and you don’t want it to be html encoded, you need to provide an IHtmlString object, or simply do:
@MvcHtmlString.Create("<b>BOLD!</b>")

By now some of you might be scratching your heads, moving anxiously in your sits or eating Ben & Jerry's uncontrollably… all of this because something is disturbing you with that line of code… something is missing…

It’s Magic! Magic!!!!!!11

Well, you were right! something is, indeed, missing… we only started the expression with the at sign, but we never told the framework where the expression ended!!! God help us all!!!

Do not worry. This is part of the charm of Razor – if your expression is a single call, there is no need to enclose it in some sort of way, you just write the expression after the at sign (and make sure it’s immediately after the at sign! for example, @ DateTime.Now will raise an exception).

Wait! But what about the times I wanna use blocks of code? or when I want to write out the result of 1 + 1? No problem, I have the solution for you! (how many times have you heard that before, right?)

So for simple expressions like additions (1 + 1, “Shay” + “ “ + “ Friedman”…) you enclose the expression in brackets. For example:

@(1 + 1)
@("Shay" + " " + "Friedman")
A Moment of Truth
What will happen if you write:
@"Shay" + " " + "Friedman"
?
... think for a moment ...
Answer: a "Parser Error" exception. Yes, get used to it.

Now, sometime you need actual code blocks like loops or conditions… and these brackets won’t help you there, son. And look carefully, because this is where it gets a bit… surprising.

Code Blocks and Razor Sitting in a Tree, K-I-S-S-I-N-G

Let’s start with the simplest use case – you want to set a variable within your view. How would you do that? @int a = 1; ? no no no. To do that, you enclose the code block within curly brackets, with an at sign at the beginning of course. For example, the next sample will output 1 to the page:

@{
    int a = 1;
}
@a

This was a very simple sample though… what about conditions for example? I’m glad you asked!

One way to write conditions (or any block of code), is by using the curly brackets solution:

@{
    string s = String.Empty;
    if (DateTime.Now.Year == 1980)
    {
        s = "Man you're so 80's!";
    }
    else
    {
        s = "It's the new millenium dude!";
    }
}
@s

This approach might become handy from time to time, but more commonly we’d want to write something out inside the condition. For these common occasions, you can use the next syntax:

@if (DateTime.Now.Year == 1980) {
    <p>Man, you're so 80's!</p>
} else {
    <p>It's the new millenium dude!</p>
}

Pay attention - it’s code and then html, and then code again, and then html again! Has your brain exploded yet?

So what happened here? in razor, everything blends together elegantly. The idea here is that razor understands when you write code and when you write html and can operate accordingly. This means that the next sample is valid as well:

@if (DateTime.Now.Year == 1983) {
    if (DateTime.Now.Month == 9) {
        <p>Wow, this month Shay is born!</p>
    } 
} else {
    <p>It's the new millenium dude!</p>
}

But this makes you ponder – is the next sample possible:

@if (DateTime.Now.Year == 1980) {
    Man, you're so 80's!
} else {
     It's the new millenium dude!
}

Though one might think it would be a valid razor syntax, it isn’t. This is because razor is smart, but it’s no genius… razor can’t tell if “Man, you’re so 80’s!” is code or html. Think of a sentence like “if pigs could fly” – is this a C# syntax error or plain text? because of this limitation, you have two options to do that – start the html part with html tags (like the previous sample that includes <p> tags) or use a <text> tag as follows:

@if (DateTime.Now.Year == 1980) {
    <text>Man, you're so 80's!</text>
} else {
     <text>It's the new millenium dude!</text>
}

Loops are very similar, too:

@{ var list = new List<string>() {"Razor","Rocks!"}; }
@foreach (var item in list) {
    <b>@item</b>
}

The Twitter Account Catastrophe

My twitter account is @ironshay, what’s yours? WAIT! WAIT!!!!111ONE all hell broke loose!!! TWITTER ACCOUNTS HAVE AN AT SIGN AT THE BEGINNING!!!!

That does it. If someone at Twitter thought about rewriting with ASP.NET MVC, now there’s no chance they’d go for it.

Hold you horses twitter! razor has a solution for you but you will have to write double at signs for that. For example, @@ironshay in a razor file will result in @ironshay in the response stream.

Here you go, Twitter can reconsider.

Read More!

This was a basic introduction to razor. If you liked what you read, I recommend you to read further and become the master of razor!

All the best,
Shay.

kick it on DotNetKicks.com Shout it



Pingbacks and trackbacks (5)+

Add comment