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
@page
<h1>Today</h1>
<p>The date is @DateTime.Now.ToString("dd MMM yyyy").</p>
<p>2 + 3 = @(2 + 3)</p>Today The date is 15 Oct 2026. 2 + 3 = 5
@DateTime.Nowprints a simple C# expression@( ... )prints the result of a calculation or a longer expression@pageat the top makes the file a Razor Page
Code Blocks
Put several C# statements inside @{ ... }:
Example
@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>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
@{
var stock = 0;
}
@if (stock > 0)
{
<p>Available: @stock items</p>
}
else
{
<p>Sorry, out of stock.</p>
}Sorry, out of stock.
Inside a C# block, Razor knows that a line starting with an HTML tag is HTML.
Loops
Example
@{
var courses = new[] { "Web Development", "Graphic Designing", "SEO" };
}
<ul>
@foreach (var course in courses)
{
<li>@course</li>
}
</ul>- Web Development - Graphic Designing - SEO
Razor Syntax Summary
| Syntax | Use |
|---|---|
@name | Print a variable |
@(a * b) | Print an expression |
@{ ... } | A block of C# statements |
@if, @foreach, @for, @switch | Control 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
@{
var comment = "<b>Nice course!</b>";
}
<p>@comment</p><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
@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?
