ASP.NET Tutorial menu

ASP.NET Razor Syntax

Razor is the syntax ASP.NET Core uses to mix C# code with HTML in .cshtml files.

The @ Symbol

In Razor, @ switches from HTML to C#. Razor then switches back to HTML by itself.

Example

cshtml
@page

<h1>Today</h1>
<p>The date is @DateTime.Now.ToString("dd MMM yyyy").</p>
<p>2 + 3 = @(2 + 3)</p>
Output
Today
The date is 15 Oct 2026.
2 + 3 = 5
  • @DateTime.Now prints a simple C# expression
  • @( ... ) prints the result of a calculation or a longer expression
  • @page at the top makes the file a Razor Page

Code Blocks

Put several C# statements inside @{ ... }:

Example

cshtml
@page
@{
    var student = "Ayesha";
    var marks = 84;
    var grade = marks >= 80 ? "A" : "B";
}

<h2>Result Card</h2>
<p>Name: @student</p>
<p>Marks: @marks</p>
<p>Grade: @grade</p>
Output
Result Card
Name: Ayesha
Marks: 84
Grade: A

Variables made in a code block can be used anywhere below it in the page.

Conditions

Example

cshtml
@{
    var stock = 0;
}

@if (stock > 0)
{
    <p>Available: @stock items</p>
}
else
{
    <p>Sorry, out of stock.</p>
}
Output
Sorry, out of stock.

Inside a C# block, Razor knows that a line starting with an HTML tag is HTML.

Loops

Example

cshtml
@{
    var courses = new[] { "Web Development", "Graphic Designing", "SEO" };
}

<ul>
@foreach (var course in courses)
{
    <li>@course</li>
}
</ul>
Output
- Web Development
- Graphic Designing
- SEO

Razor Syntax Summary

SyntaxUse
@namePrint a variable
@(a * b)Print an expression
@{ ... }A block of C# statements
@if, @foreach, @for, @switchControl flow
@* ... *@A Razor comment (never sent to the browser)
@@Print a real @ sign, as in an email
<text>...</text>Plain text inside a C# block

Safe by Default

Razor HTML-encodes everything you print with @. If a user types <script> into a form and you show it, Razor prints it as harmless text, not as a script.

Example

cshtml
@{
    var comment = "<b>Nice course!</b>";
}
<p>@comment</p>
Output
<b>Nice course!</b>

The tags appear as text, not bold. This protects your site from XSS attacks.

Only use @Html.Raw(...) for HTML you wrote yourself. Never use it on user input.

Layouts

Most pages share a header and footer from Pages/Shared/_Layout.cshtml. The layout calls @RenderBody() where each page's content goes. You can set the browser tab title from a page:

Example

cshtml
@page
@{
    ViewData["Title"] = "Admissions";
}
<h1>Admissions Open</h1>

Exercise

Exercise

How do you write a comment in a .cshtml file that is not sent to the browser?

Learn ASP.NET with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp