Razor Syntax

Razor is a syntax that you can use to create webpages in ASP.NET. The syntax makes it possible to create templates that generate well structured and clean HTML output.

Razor is easy to learn and there is a great reference here if you are planning on Using WebMatrix .

For those developing in ASP.NET MVC then this  Scott Hanselmanns blog is a good introduction to razor, you might also want to check out this video

Over on Phil Haacks blog he produced this handy razor reference chart, which I have duplicated below:

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>
Expression (Unencoded)
<span><%= model.Message %></span>
Combining Text and markup
@foreach(var item in items) {
<% 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
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
Mixing expressions and text
Hello @title. @name.
Hello <%: title %>. <%: name %>.
Comments (0)

Skip to main content