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




Comments

January 13. 2011 02:40 PM

pingback

Pingback from itwriting.com

Microsoft WebMatrix released: a simple editor for ASP.NET Razor and more, but who is the target user? « Tim Anderson’s ITWriting

itwriting.com

January 14. 2011 11:58 AM

trackback

Microsoft WebMatrix released: a simple editor for ASP.NET Razor and more, but who is the target user?

<p>Microsoft has released WebMatrix, a free tool for creating web sites for Microsoft’s web server. It uses the Web Platform Installer and installed smoothly on my Windows 7 64-bit box. What you ...

Tim Anderson

January 23. 2011 09:57 AM

pingback

Pingback from coderadio.co.il

CodeRadio » תכנית #06 – ראיון עם אלעד מידר על רובי און ריילס

coderadio.co.il

May 28. 2011 01:15 AM

pingback

Pingback from mkbed-01.miltonkeynesbedsits.co.uk

‘Grease’ Actor Jeff Conaway Dies At 60 «  miltonkeynesbedsits.co.uk

mkbed-01.miltonkeynesbedsits.co.uk

June 22. 2012 11:09 AM

pingback

Pingback from shekharshetemcts.wordpress.com

Different View Engines in MVC3 and Introduction to “Razor” syntax in ASP.NET MVC3? « Shekhar Shete MCTS

shekharshetemcts.wordpress.com

January 10. 2013 09:02 PM

www.abusiness-ideas.com

What beauty is, I know not, though it adheres to many things.

www.abusiness-ideas.com

March 2. 2013 07:42 PM

high drive travel heathrow

I have read all the comments and suggestions posted by the visitors for this article are very fine,We will wait for your next article soonly

high drive travel heathrow

March 23. 2013 07:50 AM

Mr. Mohammed Sami

Thanks for your exclusive post. I am benefited for this post, so thank you.

Mr. Mohammed Sami

March 27. 2013 07:20 PM

studentdiscount13.blogspot.com/

I really enjoyed the quality information you offer to your visitors for this blog. I will bookmark your blog and have my friends check up here often.

studentdiscount13.blogspot.com/

April 2. 2013 01:45 PM

cell phone website design

This is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! Keep up the good work.

cell phone website design

April 5. 2013 01:12 AM

radio frequency site surveys

This is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! Keep up the good work.

radio frequency site surveys

April 30. 2013 02:18 PM

freewebdesigncompanies.com

If you are a programmer or a web developer, I know that you would know for this one. It can easily be learned and I know that a lot of people are already learning.

freewebdesigncompanies.com

May 16. 2013 10:35 AM

Tuinmeubelen

this is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! Keep up the good work.
thanks!!!

Tuinmeubelen

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Subscribe Subscribe

That's Me!

Hi! I'm Shay Friedman
I'm Shay Friedman - a Visual C#/IronRuby MVP, a consultant and instructor of .NET technologies, author, speaker and new technologies freak
More about me

Contact Me

> Contact page
> Twitter: @ironshay
> LinkedIn profile

Search

Hosted By

I'm hosting this site on Arvixe and I'm very happy with it.
If you're looking for ASP.NET hosting, I highly recommend it
(and if you order from this link I also get some beer money!)
Web Hosting