Skip to main content

Razor is a template language used by ASP.NET Web Pages, ASP.NET MVC (since version 3), and ASP.NET Core. It adds a layer of abstraction above HTML generation. It supports seamless transitions between HTML markup and C# or VB code. Transitions between markup and code are indicated by the "@" sign.

Razor is a template language used by ASP.NET Web Pages, ASP.NET MVC (since version 3), and ASP.NET Core. It supports seamless transitions between HTML markup and C# or VB code. Razor files are of extension type .cshtml (for C#) and .vbhtml (for VB). Instead of a "Code Behind File" with your C# or VB code, you can inject your code in the same file with your HTML markup. Transitions between markup and code are indicated by the "@" sign.

For example, to render a simple HTML list, this C# syntax is used:

<ul>
@for (int i = 0; i < 10; i++) {
    <li>Item @i</li>
}
</ul>

To render a simple HTML list in VB, this syntax is used:

<ul>
@For i As Integer = 0 To 9
    @<li>Item @i</li>    
Next
</ul>

Razor has support for helper templates:

@helper Bold(string text) {
   return "<bold>"+text+"<bold>";
}

<p>
  This text is @Bold("bold")
<p> 

By default all string are html encoded, if you wish to avoid that use the Raw helper:

<p>@Html.Raw("<bold>hello</bold>")</p>

Occasionally you may want to include text in an escaped section, to do so use <text> or @::

@if(condition) {
 @: This is going to be rendered
}

@if(condition) {
 <text>
   This is a 
   Multiline text block 
 </text>
} 

Reference articles


  1. C# Razor Syntax Quick Reference
  2. Introduction to ASP.NET Web Programming Using the Razor Syntax (C#)
  3. Razor syntax reference for ASP.NET Core

Code Language (used for syntax highlighting): default