C# Razor Syntax Quick Reference

I gave a presentation to another team at Microsoft yesterday on ASP.NET MVC and the Razor view engine and someone asked if there was a reference for the Razor syntax.

It turns out, there is a pretty good guide about Razor available, but it’s focused on covering the basics of web programming using Razor and inline pages and not just the Razor syntax.

So I thought it might be handy to write up a a really concise quick reference about the Razor syntax.

Syntax/Sample Razor Web Forms Equivalent (or remarks)
Code Block
@{ 
  int x = 123; 
  string y = "because.";
}
<%
  int x = 123; 
  string y = "because."; 
%>
Expression (Html Encoded)
<span>@model.Message</span>
<span><%: model.Message %></span>
Expression (Unencoded)
<span>
@Html.Raw(model.Message) </span>
<span><%= model.Message %></span>
Combining Text and markup
@foreach(var item in items) {
  <span>@item.Prop</span> 
}
<% foreach(var item in items) { %>
  <span><%: item.Prop %></span>
<% } %>
Mixing code and Plain text
@if (foo) {
  <text>Plain Text</text> 
}
<% if (foo) { %> 
  Plain Text 
<% } %>
Mixing code and plain text (alternate)
@if (foo) {
  @:Plain Text is @bar
}
Same as above
Email Addresses
Hi philha@example.com
Razor recognizes basic email format and is smart enough not to treat the @ as a code delimiter
Explicit Expression
<span>ISBN@(isbnNumber)</span>
In this case, we need to be explicit about the expression by using parentheses.
Escaping the @ sign
<span>In Razor, you use the 
@@foo to display the value 
of foo</span>
@@ renders a single @ in the response.
Server side Comment
@*
This is a server side 
multiline comment 
*@
<%--
This is a server side 
multiline comment
--%>
Calling generic method
@(MyClass.MyMethod<AType>())
Use parentheses to be explicit about what the expression is.
Creating a Razor Delegate
@{
  Func<dynamic, object> b = 
   @<strong>@item</strong>;
}
@b("Bold this")
Generates a Func<T, HelperResult> that you can call from within Razor. See this blog post for more details.
Mixing expressions and text
Hello @title. @name.
Hello <%: title %>. <%: name %>.

Notice in the last example that Razor is smart enough to know that the ending period is a literal text punctuation and not meant to indicate that it’s trying to call a method or property of the expression.

Let me know if there are other examples you think should be placed in this guide. I hope you find this helpful.

What others have said

Requesting Gravatar... Shiju Varghese Jan 06, 2011 3:32 PM
# re: Razor Syntax Quick Reference
Very useful quick reference.
Requesting Gravatar... Eric Berens Jan 06, 2011 3:34 PM
# re: Razor Syntax Quick Reference
With ASP.NET 4 a new code expression syntax (<%: %>) was introduced that renders output like <%= %> blocks do – but automatically HTML encodes it before doing so. (weblogs.asp.net/...)

That being said, are all expressions HTML encoded and if so is there a syntax that outputs the expression without encoding it beforehand?
Requesting Gravatar... Damon Stephenson Jan 06, 2011 3:54 PM
# re: Razor Syntax Quick Reference
Eric: I believe @Html.Raw("text") does that now.
Requesting Gravatar... Yngve B. Nilsen Jan 06, 2011 3:57 PM
# re: Razor Syntax Quick Reference
You should also include the @* *@ compiled comment syntax.. That for me is an excellent piece of Razor-magic :)
Requesting Gravatar... Dmitry Podrezov Jan 06, 2011 4:05 PM
# re: Razor Syntax Quick Reference
To Eric Berens
@{ var text = "don't unescape me"; }
@Html.Raw(text)
Comments:
Razor

@* comments are marked like this *@

ASP.NET

<%-- comments are marked like this --%>

Another useful example:

@foreach (var item in collection) {
@* something *@
}

is parsed as well as:
@foreach (var item in collection)
{
@* something *@
}

meaning that you can move opening curly brace to the next line.
In the sample "Mixing code and plain text (alternate)" it can be mentioned that you can use razor syntax inside escaped plain text:

@if (foo) {
@:Plain Text is @value
}
Requesting Gravatar... Tomas Jansson Jan 06, 2011 4:10 PM
# re: Razor Syntax Quick Reference
Really nice quick reference guide!
Requesting Gravatar... Jonas Eriksson Jan 06, 2011 4:18 PM
# re: Razor Syntax Quick Reference
I find the @functions and @helper very useful

@functions
{
string SayWithFunction(string message)
{
return message;
}
}
@helper SayWithHelper(string message)
{

Text: @message


}
@SayWithFunction("Hello, world!")
@SayWithHelper("Hello, world!")
Requesting Gravatar... Nova Software Jan 06, 2011 4:42 PM
# re: Razor Syntax Quick Reference
Thanks, but, when will Microsoft will publish the official documents?
Requesting Gravatar... Mike Jan 06, 2011 4:47 PM
# re: Razor Syntax Quick Reference
"Notice in the last example that Razor is smart enough to know that the ending period is a literal text punctuation and not meant to indicate that it’s trying to call a method or property of the expression."

Then teach it.
Requesting Gravatar... Joe Jan 06, 2011 6:27 PM
# re: Razor Syntax Quick Reference
"Thanks, but, when will Microsoft will publish the official documents?"

+1
Requesting Gravatar... terryterry's-chicken Jan 06, 2011 8:34 PM
# re: Razor Syntax Quick Reference
I'm really impressed that you can use AddModelError on normal razor pages now. Well done Haack!

One old nuGet of a question. ViewBag? I've always thought you gave ViewData the wrong name. Call it ControlData or FormData, because it does indeed store information used by input controls. Then call ViewBag, ViewData.
Requesting Gravatar... David Carrillo (@dacanetdev) Jan 07, 2011 12:16 AM
# re: Razor Syntax Quick Reference
Very useful Quick Reference. Planning start new MVC project with Razor as View Engine
Requesting Gravatar... haacked Jan 07, 2011 12:42 AM
# re: Razor Syntax Quick Reference
Thanks for the feedback! I've incorporated many of your suggestions. @Mike, I don't understand your comment at all. Teach it what?
Requesting Gravatar... James Still Jan 07, 2011 1:03 AM
# re: Razor Syntax Quick Reference
awesome thx. the syntax is pretty straightforward I've discovered. Can you post a little something on extension helper methods? Things like Html.RadioButtonListFor? I'm still not clear on that.
Requesting Gravatar... Erx Jan 07, 2011 3:24 AM
# re: Razor Syntax Quick Reference
Please include vb razor as well... It's not cool ur ignoring 30% of developers
Requesting Gravatar... ctrlShiftBryan Jan 07, 2011 3:33 AM
# re: Razor Syntax Quick Reference
I don't seem to have @Html.Raw(). I do have MVC 3 RC2, I think. The listed version is (3.0.11029.0) is that RC2?
Requesting Gravatar... Eric Jan 07, 2011 5:14 AM
# re: Razor Syntax Quick Reference
Thanks Phil, that's a hot cubicle pinup for folks new to Razor!

Razor is awesome indeed.
Requesting Gravatar... Martin Jan 07, 2011 7:43 AM
# re: Razor Syntax Quick Reference
You have had a guide about Conditional Compilation Statements earlier, and they work fine with Razor, the color change of the condition which is not true is not working though.

But unlike WebForms, it doesnt crash the intellisense in the editor when using them.
Requesting Gravatar... Bas Jansen Jan 08, 2011 7:07 PM
# re: Razor Syntax Quick Reference
It seems that MVC 3 is RTM because of a checking in the Orchard Project (orchard.codeplex.com/.../403731d7ad50). Bit strange too find it out like this. But nevertheless congratulations!

Requesting Gravatar... Rodrigo Caballero Jan 09, 2011 5:40 AM
# re: Razor Syntax Quick Reference
Hi Phil,
I'm using the Telerik extensions for ASP.NET MVC and there's the following code for the webforms engine:
<% Html.Telerik().PanelBar()
.Name("PanelBar")
.Items(items =>
{
items.Add()
.Content(() =>
{
%>
<span>This is content inside a method</span>
<%
});
})
%>

I can't make it run with razor sintax ( not even with parenthesis characters around the spans). Note that Webforms sintax is "closing" the code definition for a while, pastes a little html markup and then keeps working with the rest of the method's code

How about this kind of webforms well-working functionality on razor?

best regards
Rodrigo

PD. more of this case on:
demos.telerik.com/aspnet-mvc/panelbar/templates
Requesting Gravatar... Andrey Taritsyn Jan 09, 2011 7:48 PM
# re: Razor Syntax Quick Reference
Hi, Rodrigo!

Try the following code:

@(Html.Telerik().PanelBar()
.Name("PanelBar")
.Items(items => items
.Add().Content(@<span>This is content inside a method</span>)
)
)

In Telerik Blogs is a good article on this subject - blogs.telerik.com/....
Requesting Gravatar... Developer Seer Jan 10, 2011 10:28 PM
# re: Razor Syntax Quick Reference
Phil I'm eager to ask this to someone.

What is the performance loose for this awesomeness?
I mean is this analyzed during runtime?
or is it compiled in any form?

Thanks!
Requesting Gravatar... arootbeer Feb 24, 2011 2:25 AM
# re: Razor Syntax Quick Reference
What is the correct way to make generic method calls in razor? I don't seem to be able to google it appropriately :)

I want to be able to do


<td>@MyStringMethod<MyClass>(params)</td>
Requesting Gravatar... haacked Feb 24, 2011 12:29 PM
# re: Razor Syntax Quick Reference
Make it an explicit expression.

@(MyStringMethod<MyClass>(params))
Requesting Gravatar... arootbeer Feb 25, 2011 5:07 AM
# re: Razor Syntax Quick Reference
Ah, okay. Might I suggest updating your table with that? The example explicit expression doesn't really seem to address the point of explicit expressions AFAICT.

Thanks for the tip, and a useful post.
Requesting Gravatar... haacked Feb 25, 2011 8:57 AM
# re: Razor Syntax Quick Reference
@arootbeer done!
Requesting Gravatar... michael herndon Feb 27, 2011 7:45 AM
# re: Razor Syntax Quick Reference
So when is this post going to be put into first Razor Syntax quick cheat sheet (pdf / exportable format version) ?
Requesting Gravatar... Stuart Mar 11, 2011 2:10 AM
# re: Razor Syntax Quick Reference
How can I use the <asp:calendar> control in a webmatrix cshtml page? Is this possible?
Requesting Gravatar... wtq Mar 30, 2011 6:01 PM
# re: Razor Syntax Quick Reference
I don't know what the meaning of <text></text>in the mvc3
Requesting Gravatar... Gareth Elms Apr 06, 2011 6:24 PM
# re: Razor Syntax Quick Reference
I should have read this last night before twanting (Twitter ranting) about Razor, I'd regard having to use @: as a gotcha. I started using Razor last night, and I've heard a lot about how Razor means you don't need to think about the code/markup separation, but it's not strictly true and I hit this gotcha immediately


@if( Request.IsAuthenticated){
Hello @Page.User.Identity.Name
}else{
@Html.ActionLink( "Log On", "LogOn", "Account")
}
Requesting Gravatar... Gareth Elms Apr 06, 2011 8:13 PM
# re: Razor Syntax Quick Reference
@wtg <text> is a fake html tag that helps Razor know to flip out of server code parsing and into markup parsing. The text tag is actually rendered but it is invalid html/xhtml. So it's not ideal. Use @: instead
Requesting Gravatar... haacked Apr 07, 2011 2:45 PM
# re: Razor Syntax Quick Reference
Well yeah, there's always going to be those cases where you do have to think about it. After all, there's no way for Razor to know in that case that you meant for that to be literal text unless you tell it.

But in most cases (at least in my experience), I start such blocks with a tag, such as a SPAN. In that case, it really does flow.
Requesting Gravatar... sandeep Apr 10, 2011 5:34 AM
# how to apply dynamically classes on div in MVC3 (Razor)
hi,

i am working on mvc3 project using Razor view engine.

i have to apply dynamically classes on div.

my syntax is given below:



@{
View.Title = "About Us";
}


<h2>About</h2>
@using(Html.BeginForm("About","HomeController")){

int section = 0;
if (section == 0)
{
<div class="student">
}
else
{
<div class="teacher">
}

</div>


}



At runtime it gives below error:

Parser Error Message: The using block is missing a closing "}" character. Make sure you have a matching "}" character for all the "{" characters within this block, and that none of the "}" characters are being interpreted as markup.

how we can handle such dynamic design conditions
Requesting Gravatar... Meriem Apr 10, 2011 5:11 PM
# re: Razor Syntax Quick Reference
Hi, please i want the syntaxe in razor of the ajax toolkit calendar "<asp:calendar ...
Please help.. Thank you!
Requesting Gravatar... Ethan Apr 20, 2011 10:54 AM
# re: Razor Syntax Quick Reference
Awesome, cooked and ready! thanks
Requesting Gravatar... Darshan May 24, 2011 8:32 PM
# re: Razor Syntax Quick Reference
Phill u saved my time. thank you for quick guide.
Requesting Gravatar... Arvin Boggs May 30, 2011 11:27 AM
# re: Razor Syntax Quick Reference
Please change the title to "C# Razor Syntax Quick Reference".
Requesting Gravatar... Ehsan Aug 18, 2011 11:47 PM
# re: C# Razor Syntax Quick Reference
Very useful
Thanks
Requesting Gravatar... Sharmin Aug 23, 2011 7:29 AM
# re: C# Razor Syntax Quick Reference
Nice small article.
Requesting Gravatar... Deany Web Geek Oct 26, 2011 4:16 AM
# re: C# Razor Syntax Quick Reference
Excellent, very useful :)
Requesting Gravatar... estetik Jan 17, 2012 11:22 PM
# re: C# Razor Syntax Quick Reference
good article.
thanks
Requesting Gravatar... Joe Feb 04, 2012 10:39 PM
# re: C# Razor Syntax Quick Reference
Great post! This will come in handy. Thanks!
Requesting Gravatar... David Willington Mar 19, 2012 8:34 AM
# re: C# Razor Syntax Quick Reference
I've hit a problem with the following code

<ul>

@foreach (var venue in Model.venues) {
<li id='vc_@Html.Raw(venue.code)'>@Html.Raw(venue.name)</li>
}

</ul>


The output is

<ul>

<li id='vc_@Html.Raw(venue.code)'>Venue 1</li>
<li id='vc_@Html.Raw(venue.code)'>Venue 2</li>
<li id='vc_@Html.Raw(venue.code)'>Venue 3</li>
</ul>


I can't see how to have the @Html.Raw(venue.code) parsed. The best I've come up with so far is to try and escape the @Html.Raw(venue.code), ie \@Html.Raw(venue.code) which means the code is parsed but I get the \ in the output, ie


<ul>
<li id='vc_\v1'>Venue 1</li>
<li id='vc_\v2'>Venue 2</li>
<li id='vc_\v3'>Venue 3</li>
</ul>


I think this would do, but it's not what I'm after (I'd like to avoid the \ character in the output). Can anyone suggest a way round it?

Thanks
Requesting Gravatar... Alan G Apr 17, 2012 9:10 PM
# re: C# Razor Syntax Quick Reference
This syntax should work:

<li id='vc_@(Html.Raw(venue.code))'>@Html.Raw(venue.name)</li>
Requesting Gravatar... Alex Ilyin Apr 25, 2012 5:19 AM
# re: C# Razor Syntax Quick Reference
Thanks for post
Requesting Gravatar... Kevin Dietz May 13, 2012 6:44 PM
# re: C# Razor Syntax Quick Reference
Good resource.

Things to add: @using to reference namespaces, @model to declare the type of the model, @RenderSection to insert a section (content placeholder), and @section to declare section used by @RenderSection, and a full quick reference for all @Html calls. Thanks.

What do you have to say?

(will show your gravatar)
Please add 7 and 8 and type the answer here: