Inline Razor Syntax Overview

4.26 (23 votes)

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.

 

You might also like...

Date Posted:
Last Updated:
Posted by:
Total Views to date: 95650

16 Comments

- reav

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

Keep it going!

- 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

- 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.

- dotnetcoder

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

- Sam

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

- Steve

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

case 1:
message = "Case 1";

rather than

case: 1
message = "Case 1";

- Mike

@Steve,

Good spot. Corrected now.

- Harsha

Good information, thanks a lot.

- 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.

- Mike

@Gianmaria,

Well spotted!

- commonPerson

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

- Michael Easterbrook

When I have the following code:

@foreach (var procRow in procRowDecade)
{
if (@procRow[3] + procRow[8] > 0)
{
NAPct = Convert.ToDecimal(@procRow[3]) / (@procRow[3] + procRow[8]);
}
}

I get this error:

Error 3 } expected

- Mike

@Michael,

You should remove the @ symbols in form of variables in the if statement. You only use the @ symbol with a variable if you intend to render its value to the browser.

- Michael Easterbrook

I removed the @ symbols and I am still getting the same error. It only occurs when I have an "if" inside a "foreach".

- Mike

@Michael,

It's difficult to know from what you posted if there isn't another cause for your issue. You would be better off posting a question showing more code in the ASP.NET forums

- Rama

the sample below this explanation
"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:"

was really helpful

Recent Comments

Sivu 19/10/2016 08:21
In response to Entity Framework Core TrackGraph For Disconnected Data
Oh that's very very very nice ! Thanks for the write up Mike, much appreciated for the taking the to...

Mark 12/10/2016 16:42
In response to ASP.NET Web Pages vNext or Razor Pages
Although "Web Pages" was removed from the roadmap, has it just been renamed to "Razor Pages"?...

Satyabrata 12/10/2016 09:20
In response to Entity Framework Core TrackGraph For Disconnected Data
Nice article. Please write more articles featuring ASP.Net web pages. Thank you...

Julian 26/09/2016 14:27
In response to Loading ASP.NET Core MVC Views From A Database Or Other Location
Fantastic, many thanks Mike! Had got half way down this road before finding your article - saved...

Abolfazl Roshanzamir 14/09/2016 05:36
In response to Loading ASP.NET Core MVC Views From A Database Or Other Location
Nice article. Thanke you so much ....

cyrus 02/09/2016 15:12
In response to ASP.NET Web Pages vNext or Razor Pages
I've got some news. As Damian stated in this link: https://github.com/aspnet/Mvc/issues/5208 “We...

Simon 01/09/2016 08:00
In response to Loading ASP.NET Core MVC Views From A Database Or Other Location
Thanks Mike, nice post and exactly what I was looking for. Like you said, I think I'll opt to the...

dave 20/08/2016 14:57
In response to ASP.NET Web Pages vNext or Razor Pages
Do SimplemembershipProvider in viewpages is supported?...

Steven 18/08/2016 04:40
In response to Entity Framework Code First and Stored Procedures
Can you provide the directives (using statements) you're using for EF7 example?...

yousaid 17/08/2016 22:08
In response to ASP.NET Web Pages vNext or Razor Pages
Increasingly, learning a Microsoft tool is no longer worth the return on investment. Too many tools...