C# Razor Syntax
Introduction
Razor is a markup syntax that lets you embed server-based C# code into webpages. It's a fundamental part of ASP.NET Core's MVC and Razor Pages frameworks, allowing developers to create dynamic web content that seamlessly blends HTML with C# logic.
Razor syntax provides a clean, lightweight way to create server-rendered HTML without the verbosity of traditional ASP.NET Web Forms. Using Razor, you can write web pages that execute C# on the server before sending HTML to the browser, enabling dynamic content generation while maintaining clear separation between markup and logic.
In this guide, we'll explore the basics of Razor syntax, how it works, and how you can use it to build dynamic web applications.
Razor Basics
File Extensions
Razor files use specific extensions depending on how they're used:
.cshtml
- Razor views used in MVC or Razor Pages.razor
- Razor components used in Blazor (component-based framework)
The @ Symbol
The foundation of Razor syntax is the @
symbol, which transitions from HTML to C# code. When Razor sees @
, it knows that what follows is C# code that needs to be executed rather than output as literal text.
Here's a simple example:
<div>
<h1>Hello, @Model.Username!</h1>
<p>The current time is: @DateTime.Now</p>
</div>
In this example, @Model.Username
and @DateTime.Now
are C# expressions that will be evaluated and their values inserted into the HTML output.
Razor Expressions
Inline Expressions
The simplest form of Razor syntax is the inline expression, which outputs the value of a variable or expression:
@{
var message = "Welcome to Razor!";
var currentYear = DateTime.Now.Year;
}
<h1>@message</h1>
<p>Copyright © @currentYear</p>
Output:
<h1>Welcome to Razor!</h1>
<p>Copyright © 2023</p>
Code Blocks
For more complex C# logic, you can use code blocks with @{ ... }
:
@{
var totalItems = 5;
var price = 20.50;
var totalCost = totalItems * price;
}
<h2>Order Summary</h2>
<p>Items: @totalItems</p>
<p>Price per item: $@price</p>
<p>Total: $@totalCost</p>
Output:
<h2>Order Summary</h2>
<p>Items: 5</p>
<p>Price per item: $20.5</p>
<p>Total: $102.5</p>
Handling Text with @ Symbol
If you need to use the @
symbol literally in your output, you can escape it by using a double @@
:
<p>Contact us at support@@example.com</p>
Output:
<p>Contact us at [email protected]</p>
Control Structures
Razor supports all C# control structures like if statements, switches, loops, and more.
If Statements
@{
bool isLoggedIn = true;
string userName = "JohnDoe";
}
@if (isLoggedIn)
{
<div class="welcome-message">Welcome back, @userName!</div>
}
else
{
<div class="login-prompt">Please log in to continue</div>
}
Output (when isLoggedIn is true):
<div class="welcome-message">Welcome back, JohnDoe!</div>
Loops
For loops, foreach loops, and other iterative structures work seamlessly with Razor:
@{
string[] fruits = { "Apple", "Banana", "Cherry", "Date" };
}
<h3>Fruit List</h3>
<ul>
@foreach (var fruit in fruits)
{
<li>@fruit</li>
}
</ul>
Output:
<h3>Fruit List</h3>
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
<li>Date</li>
</ul>
Switch Statements
@{
var day = DateTime.Now.DayOfWeek;
}
<p>
Today's special:
@switch (day)
{
case DayOfWeek.Monday:
<span>Meatball Monday</span>
break;
case DayOfWeek.Tuesday:
<span>Taco Tuesday</span>
break;
case DayOfWeek.Wednesday:
<span>Wing Wednesday</span>
break;
default:
<span>Chef's Special</span>
break;
}
</p>
Implicit and Explicit Transitions
Implicit Transitions
When using @
followed by a variable or expression, Razor automatically knows where the C# code ends:
<p>The square of 5 is @(5 * 5)</p>
<p>Today is @DateTime.Now.DayOfWeek</p>
Explicit Transitions with Parentheses
Sometimes Razor needs help determining where expressions end. Use parentheses for explicit transitions:
<p>The product is @(price * quantity)</p>
<p>The first item is @(items[0])</p>
Without parentheses, Razor might interpret the asterisk as an HTML element or get confused by special characters.
Rendering HTML Content
Raw HTML Output
By default, Razor HTML-encodes string output for security. To output raw HTML, use the Html.Raw()
helper:
@{
string htmlContent = "<strong>This is bold text</strong>";
}
<p>Encoded: @htmlContent</p>
<p>Raw: @Html.Raw(htmlContent)</p>
Output:
<p>Encoded: <strong>This is bold text</strong></p>
<p>Raw: <strong>This is bold text</strong></p>
⚠️ Security Warning: Only use Html.Raw()
with content you trust. Never use it with user-provided input as it may lead to cross-site scripting (XSS) vulnerabilities.
Comments in Razor
Razor supports both HTML and C# style comments:
@* This is a Razor comment - it won't appear in the rendered HTML *@
<!-- This is an HTML comment - it will appear in the rendered HTML -->
@{
// This is a C# comment inside a code block
/* This is a multi-line
C# comment */
}
Practical Examples
Example 1: Dynamic Table Generation
This example shows how to dynamically generate an HTML table from a collection of data:
@{
var products = new[] {
new { Id = 1, Name = "Laptop", Price = 999.99 },
new { Id = 2, Name = "Smartphone", Price = 599.99 },
new { Id = 3, Name = "Headphones", Price = 149.99 }
};
}
<h2>Product List</h2>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody>
@foreach (var product in products)
{
<tr>
<td>@product.Id</td>
<td>@product.Name</td>
<td>[email protected]("0.00")</td>
</tr>
}
</tbody>
</table>
Example 2: Conditional Styling with Razor
This example demonstrates how to apply CSS classes based on conditional logic:
@{
var tasks = new[] {
new { Id = 1, Title = "Complete project", IsCompleted = true },
new { Id = 2, Title = "Review code", IsCompleted = false },
new { Id = 3, Title = "Deploy application", IsCompleted = false }
};
}
<h2>Task List</h2>
<ul class="task-list">
@foreach (var task in tasks)
{
<li class="task @(task.IsCompleted ? "completed" : "pending")">
<span class="task-title">@task.Title</span>
<span class="task-status">
@if (task.IsCompleted)
{
<span class="badge bg-success">Done</span>
}
else
{
<span class="badge bg-warning">Pending</span>
}
</span>
</li>
}
</ul>
Example 3: Form Processing Logic
This example shows how Razor can handle form processing logic:
@{
var name = Request.Query["name"].ToString();
var email = Request.Query["email"].ToString();
var submitted = !string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(email);
}
@if (submitted)
{
<div class="alert alert-success">
<p>Thank you for your submission, @name!</p>
<p>We'll contact you at @email soon.</p>
</div>
}
else
{
<form method="get" action="">
<div class="mb-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name" name="name" required>
</div>
<div class="mb-3">
<label for="email" class="form-label">Email</label>
<input type="email" class="form-control" id="email" name="email" required>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
}
Advanced Razor Features
Sections
Sections allow you to define parts of a page that can be rendered in specific locations in a layout:
@section Scripts {
<script src="~/js/product-details.js"></script>
}
@section Styles {
<link href="~/css/product-details.css" rel="stylesheet" />
}
In your layout file, you'd render these sections with:
<head>
<!-- Other head elements -->
@RenderSection("Styles", required: false)
</head>
<body>
<!-- Body content -->
@RenderBody()
<!-- Scripts at the end -->
@RenderSection("Scripts", required: false)
</body>
Partial Views
Partial views allow you to reuse components across multiple pages:
<div class="sidebar">
<partial name="_LoginPartial" />
<partial name="_NavigationPartial" />
</div>
Tag Helpers
Tag Helpers enable server-side code to participate in creating and rendering HTML elements:
<form asp-controller="Account" asp-action="Login" method="post">
<div class="form-group">
<label asp-for="Username"></label>
<input asp-for="Username" class="form-control" />
<span asp-validation-for="Username" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
Summary
Razor syntax provides an elegant way to combine C# and HTML to create dynamic web content in ASP.NET Core applications. With its intuitive @
symbol for transitions between markup and code, Razor enables clean, readable templates while maintaining the full power of C#.
Key points to remember:
- Use
@
to transition from HTML to C# code - Code blocks are wrapped in
@{ ... }
- Control structures like
@if
,@foreach
, etc. work seamlessly with HTML - Use
@(expression)
when you need to be explicit about where expressions end - Be careful with
Html.Raw()
to prevent security vulnerabilities - Razor views are compiled, giving you IntelliSense and compile-time error checking
By mastering Razor syntax, you can create dynamic, data-driven web applications that combine the best of server-side logic with clean HTML output.
Additional Resources
Practice Exercises
- Create a Razor page that displays a list of your favorite books with details like title, author, and publication year.
- Implement a simple calculator using Razor that takes two numbers as input and displays their sum, difference, product, and quotient.
- Create a "User Profile" page that conditionally displays different content based on user roles (admin, regular user, guest).
- Build a product listing page with pagination using Razor syntax.
- Implement a comment system that allows users to submit comments and displays them with proper formatting and timestamps.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)