Inline Razor Syntax Overview

With the launch of WebMatrix, and the announcement of the new Razor View Engine for the next version of ASP.NET MVC, here's a quick guide to Razor syntax.

All code blocks must appear within @{ ... } brackets. As soon as you type @, you are assumed to have started writing code. Everything that follows is assumed to be code, unless you tell Razor otherwise:

@{
    var numbers = Enumerable.Range(1, 10); //Get numbers from 1 - 10
    foreach(var number in numbers){
            
   }
}

If you want to render the variable number within the loop above, you have to prefix it with an @ sign:

@{
    var numbers = Enumerable.Range(1, 10); //Get numbers from 1 - 10
    foreach(var number in numbers){
           @number
    }
}

If you want to render the result of a single line expression, you use the @( ... ) syntax:

@{
    var numbers = Enumerable.Range(1, 10); //Get numbers from 1 - 10
    foreach(var number in numbers){
        @(number * 10)
    }
}

If you want to mix inline variables with items to be rendered literally (verbatim strings) within a code block, there are three ways to tell Razor where the code pauses and the literal text or markup begins. The first, if the additional item is text only, is to prefix the text with @: before the first instance of text in the line:

@{
    var numbers = Enumerable.Range(1, 10); //Get numbers from 1 - 10
    foreach(var number in numbers){
        @(number * 10)@: 
    }
}

You only need to use the @: operator once per line:

@{
    var numbers = Enumerable.Range(1, 10); //Get numbers from 1 - 10
    foreach(var number in numbers){
        @(number * 10)@: * 10 = @(number * 10)
    }
}

Razor also looks for html tags. If it sees one, it jumps out of code and will only jump back into code when it sees a matching closing tag:

@{
    var numbers = Enumerable.Range(1, 10); //Get numbers from 1 - 10
    foreach(var number in numbers){
        <span>@(number * 10)&nbsp;</span>
    }
}

Razor can recognise self-closing tags:

@{
    var numbers = Enumerable.Range(1, 10); //Get numbers from 1 - 10
    foreach(var number in numbers){
        @(number * 10)<br />
    }
}

If you do not want to render html tags, you can use the <text> tag to tell Razor where code ends and begins again. The <text> tag is not rendered to the browser:

@{
    var numbers = Enumerable.Range(1, 10); //Get numbers from 1 - 10
    foreach(var number in numbers){
        <text>@(number * 10) * 10 = @(number * 10)&nbsp;</text>
    }
}

Comments within a code block can denoted by two forward slashes //, as can be seen in all the preceding examples. Alternatively, you can use /*...*/ or @*...*@. If you want to put a server side comment outside of a code block, precede the line @*

@{
    /*Get numbers from 1 - 10*/
    //Get numbers  between 1 - 10
    @*Get numbers between 1 - 10*@
    var numbers = Enumerable.Range(1, 10); 
    foreach(var number in numbers){
        @number
    }
}

The following example illustrates two things - the first is commenting outside of code blocks using the @*...*@ syntax. The second is that iteration and selection statement keywords (if, for, foreach, switch, while etc) do not need curly braces before them. A simple @ sign will do. The same is true for try... catch, if you want to use that particular construct inline.

@* Get numbers between 1 - 10 *@

@{ var numbers = Enumerable.Range(1, 10); }

@foreach(var number in numbers){
    @number
}

@for(var i = 0; i < numbers.Count(); i++){
    @numbers.ElementAt(i)
}

@if(numbers.Count() == 10){
    @:10 Numbers - Good!   
}

@{var condition = 1; var message = "";}

@switch(condition){
    case 1:
        message = "Case 1";
        break;
    case 2:
        message = "Case 2";
        break;
    case 3:
        message = "Case 3";
        break;
    default:
        message = "Default Case";
        break;
}

@message

This article covers all of the basics needed to use Razor within ASP.NET Web Pages, and should provide a ready reference for those using the Razor View Engine within ASP.NET MVC 3 onwards. If you would like to know more about how the Razor parser actually works, and track its evolution, you should visit the blog of Dr Razor - Andrew Nurse.

 

Date Posted: Friday, July 30, 2010 3:27 PM
Last Updated: Wednesday, May 23, 2012 9:50 PM
Posted by: Mikesdotnetting
Total Views to date: 67367

11 Comments

Sunday, August 1, 2010 4:38 PM - reav

Nice to see new posts about razor! Thank you very much!

Keep it going!

Wednesday, August 4, 2010 11:14 AM - Shady

Clear as mud.

I know webform viewsaren't exactly a paradigm of simplicity, but a glance will tell you what's going on (unless it's a contorted example), but these modest examples of Razor syntax look confusing at first glance - i mishmash of @'s, symbols, braces, with no *clear* demarcation between code and markup.

How does it deal with email addresses?

I will give it a go, but I don't understand why so much effort was put into something that ended up looking like a cross between Coldfusion and Perl

Wednesday, August 4, 2010 11:56 AM - Mike

@Shady,

Razor appears to handle email addresses just fine, and in most cases can work out that the @ sign is not an indicator of code. Where it might be parsed as such, you can just escape it: @@

By the way, there's nothing to say you *have* to use Razor. When it's made available within ASP.NET Web Forms, it simply an additional option.

Wednesday, August 11, 2010 10:25 PM - dotnetcoder

Awesome! Thank you. Please keep these articles coming - they are the best.

Friday, January 28, 2011 9:34 PM - Sam

Great Article. I was stuck on figuring out how to initialize a variable above a loop. Your article helped! Thanks!!!

Monday, March 5, 2012 3:10 PM - Steve

The colon is wrong in the case statement. It should be

case 1:
message = "Case 1";

rather than

case: 1
message = "Case 1";

Monday, March 5, 2012 4:55 PM - Mike

@Steve,

Good spot. Corrected now.

Wednesday, May 23, 2012 6:43 AM - Harsha

Good information, thanks a lot.

Wednesday, May 23, 2012 9:44 PM - GmGregori

I suggest you two more small corrections:

@for(var i = 0; i < numbers.Count(); i++){
instead of
@for(var i = 0, i < numbers.Count(); i++){

and

@{var condition = 1; var message = "";}
instead of
@{var condition = 1; var message = ""}

Great article.

Wednesday, May 23, 2012 9:52 PM - Mike

@Gianmaria,

Well spotted!

Tuesday, July 2, 2013 2:45 PM - commonPerson

Examples are very helpful thanks! Please keep these articles coming...
Add your comment

If you have any comments to make about this article, please use this form to do so. Make sure that your comment relates specifically to the article above. More general comments can be posted through the form on the Contact page.

Please note, all comments are moderated, and some may not be published. The kind of things that will ensure your comment is deleted without ever seeing the light of day are as follows:

  • Not relevant to the article
  • Gratuitous links to your own site or product
  • Anything abusive or libellous
  • Spam
  • Anything in a language I don't understand including gibberish.

I do not pass email addresses on to spammers, so a valid one will assist me in responding to you personally if required.

Recent Comments

Bino 11/27/2014 7:05 PM
In response to MVC 5 with EF 6 in Visual Basic - Async and Stored Procedures with the Entity Framework
Copy +...

Manas 11/27/2014 5:30 AM
In response to Scheduled Tasks In ASP.NET With Quartz.Net
Hi Mike, Thank you for awesome article. My concern is it might impact website if we use or is...

priya 11/26/2014 6:50 PM
In response to Create PDFs in ASP.NET - getting started with iTextSharp
very nice.....its save my time...

ransems 11/24/2014 12:29 AM
In response to Adding A Controller
Love the article. I dislike that the world thinks c# articles are the way to go. Love the VB, keep...

Gautam 11/20/2014 8:01 AM
In response to I'm Writing A Book On WebMatrix
Hello Mike, I read your book, loved it! However, I have a few request/suggestions: 1) an example...

Bret Dev 11/19/2014 8:39 PM
In response to The Difference Between @Helpers and @Functions In WebMatrix
Excellent post! One concern - where can you place global @Functions code within an MVC project to Is...

Rob Farquharson 11/19/2014 4:28 PM
In response to iTextSharp - Links and Bookmarks
How can I place text at an absolute position on the page? Also, how can I rotate text?...

Andy 11/17/2014 8:08 PM
In response to MVC 5 with EF 6 in Visual Basic - Sorting, Filtering and Paging
Hello I'm testing your sorting instructions above. This is great and I was able to get it to work...

Gautam 11/17/2014 5:51 PM
In response to WebMatrix - Database Helpers for IN Clauses
Hi Mike, I am very new to programming: In the above example if I want to use a delete button the...

donramon 11/17/2014 3:22 PM
In response to Entity Framework 6 Recipe - Alphabetical Paging In ASP.NET MVC
Congratulations on your new website look and the excellent articles. Thank you!...