.NET Razor Syntax
Introduction
Razor is a markup syntax that enables you to embed server-based code (C# or Visual Basic) into webpages. It's the default templating language for ASP.NET Core MVC and Blazor applications, providing a way to create dynamic web content by seamlessly combining HTML with server-side code.
What makes Razor powerful is its ability to let you switch between HTML and C# with minimal additional markup, making your code cleaner and easier to maintain. If you're familiar with HTML and have some knowledge of C#, you'll find Razor intuitive to learn and use.
In this guide, we'll explore the fundamentals of Razor syntax, how to use it effectively, and implement real-world examples to help you build dynamic web applications.
Razor Syntax Fundamentals
The @ Symbol: Transitioning from HTML to C#
The core of Razor syntax is the @ symbol, which tells the compiler to switch from HTML to C#.
<div>
<p>The current time is: @DateTime.Now</p>
<p>Today is: @DateTime.Now.DayOfWeek</p>
</div>
Output:
<div>
<p>The current time is: 9/23/2023 10:30:45 AM</p>
<p>Today is: Saturday</p>
</div>
Executing C# Statements
For more complex C# code, you can use code blocks enclosed in @{ ... }:
@{
var greeting = "Hello, World!";
var currentHour = DateTime.Now.Hour;
var message = currentHour < 12 ? "Good morning!" : "Good day!";
}
<h1>@greeting</h1>
<p>@message</p>
Output:
<h1>Hello, World!</h1>
<p>Good morning!</p>
(Output will depend on the current time)
Conditional Statements in Razor
Razor makes it easy to include conditional logic directly in your views:
@{
var isLoggedIn = true;
var username = "JohnDoe";
}
@if (isLoggedIn)
{
<p>Welcome back, @username!</p>
}
else
{
<p>Please <a href="/login">log in</a> to continue.</p>
}
Output:
<p>Welcome back, JohnDoe!</p>
Working with Loops
Loops are essential for displaying collections of data:
@{
string[] fruits = { "Apple", "Banana", "Cherry", "Date", "Elderberry" };
}
<h2>Fruit List</h2>
<ul>
@foreach (var fruit in fruits)
{
<li>@fruit</li>
}
</ul>
Output:
<h2>Fruit List</h2>
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
<li>Date</li>
<li>Elderberry</li>
</ul>
Advanced Razor Features
Comments
Razor allows both HTML and Razor-specific comments:
@* This is a Razor comment and won't appear in the rendered HTML *@
<!-- This is an HTML comment that will be visible in the source code -->
<p>This text will be visible on the page.</p>
HTML Encoding and Raw Output
By default, Razor HTML-encodes content to prevent cross-site scripting (XSS) attacks. Sometimes, you may want to render raw HTML:
@{
var encodedContent = "<strong>This won't be bold</strong>";
var rawContent = "<strong>This will be bold</strong>";
}
<p>Encoded output: @encodedContent</p>
<p>Raw output: @Html.Raw(rawContent)</p>
Output:
<p>Encoded output: <strong>This won't be bold</strong></p>
<p>Raw output: <strong>This will be bold</strong></p>
⚠️ Warning: Use
Html.Raw()with caution, as it can expose your application to XSS vulnerabilities if used with untrusted content.
Using Explicit Expressions
For complex expressions, you can use explicit expressions with parentheses:
<p>The result of 5 * 3 + 2 is @(5 * 3 + 2)</p>
<p>The first letter of the alphabet: @("ABCDEFG".ToLower()[0])</p>
Output:
<p>The result of 5 * 3 + 2 is 17</p>
<p>The first letter of the alphabet: a</p>
Working with Email Addresses
When you have an @ symbol in text (like email addresses), you need special handling:
<p>Contact us at: support@@example.com</p>
<p>Alternative: @("[email protected]")</p>
Output:
<p>Contact us at: [email protected]</p>
<p>Alternative: [email protected]</p>
Real-World Application: A Dynamic Product List
Let's build a simple dynamic product list that could be part of an e-commerce application:
@{
var products = new List<Product>
{
new Product { Id = 1, Name = "Laptop", Price = 999.99m, InStock = true },
new Product { Id = 2, Name = "Smartphone", Price = 499.99m, InStock = true },
new Product { Id = 3, Name = "Headphones", Price = 149.99m, InStock = false },
new Product { Id = 4, Name = "Monitor", Price = 299.99m, InStock = true }
};
}
<h2>Our Products</h2>
<div class="product-list">
@foreach (var product in products)
{
<div class="product-card @(product.InStock ? "" : "out-of-stock")">
<h3>@product.Name</h3>
<p class="price">[email protected]("0.00")</p>
@if (product.InStock)
{
<button class="buy-button">Add to Cart</button>
}
else
{
<p class="stock-status">Out of Stock</p>
<button class="notify-button">Notify Me</button>
}
</div>
}
</div>
@code {
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public bool InStock { get; set; }
}
}
This example demonstrates:
- Creating a model class within the view (though in real applications, you'd typically use a separate model)
- Looping through a collection
- Conditional rendering based on product properties
- String formatting
- Dynamic CSS class application
Working with Layouts and Partial Views
Layout Pages
Razor layouts provide a consistent structure for your application:
<!-- _Layout.cshtml -->
<!DOCTYPE html>
<html>
<head>
<title>@ViewData["Title"] - My Site</title>
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
<header>
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
<a href="/contact">Contact</a>
</nav>
</header>
<main>
@RenderBody()
</main>
<footer>
© @DateTime.Now.Year - My Website
</footer>
@RenderSection("Scripts", required: false)
</body>
</html>
Using the Layout in a View
@{
ViewData["Title"] = "Home Page";
Layout = "_Layout";
}
<h1>Welcome to our website!</h1>
<p>This is the homepage content.</p>
@section Scripts {
<script>
document.addEventListener('DOMContentLoaded', function() {
console.log('Homepage loaded!');
});
</script>
}
Partial Views
Partial views let you break down complex pages into reusable components:
<!-- _ProductCard.cshtml -->
@model Product
<div class="product-card @(Model.InStock ? "" : "out-of-stock")">
<h3>@Model.Name</h3>
<p class="price">[email protected]("0.00")</p>
@if (Model.InStock)
{
<button class="buy-button">Add to Cart</button>
}
else
{
<p class="stock-status">Out of Stock</p>
<button class="notify-button">Notify Me</button>
}
</div>
Using the partial view:
<h2>Our Products</h2>
<div class="product-list">
@foreach (var product in products)
{
<partial name="_ProductCard" model="product" />
}
</div>
Tag Helpers
Tag Helpers are a powerful feature in ASP.NET Core that enable server-side code to participate in creating and rendering HTML elements:
<!-- Using a form tag helper -->
<form asp-controller="Account" asp-action="Login" method="post">
<div class="form-group">
<label asp-for="Email"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password"></label>
<input asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
Summary
Razor syntax provides a powerful and elegant way to combine HTML and C# code in ASP.NET web applications. In this guide, we've covered:
- The basics of using the
@symbol to transition between HTML and C# code - How to work with expressions, statements, and code blocks
- Conditional rendering and loops
- HTML encoding and security considerations
- Advanced techniques with explicit expressions
- Real-world examples of dynamic content generation
- Layouts, partial views, and tag helpers for building structured applications
Mastering Razor syntax is essential for building dynamic, data-driven ASP.NET web applications. The syntax is designed to be intuitive for both HTML and C# developers, making it accessible even for beginners while providing powerful capabilities for advanced scenarios.
Additional Resources
To continue learning about Razor syntax, explore these resources:
Exercises
-
Simple Calculator: Create a Razor page that takes two numbers as parameters and displays their sum, difference, product, and quotient.
-
Todo List: Build a simple todo list application that stores tasks in a
List<T>and allows users to add, mark completed, and delete tasks. -
Data Table: Create a view that displays data from a collection in a HTML table, with alternating row colors and the ability to highlight specific rows based on data conditions.
-
Form Helper: Create a reusable partial view that generates a standardized form group with label, input, and validation message for different data types.
-
Navigation Menu: Build a dynamic navigation menu that highlights the current page and renders different menu items based on user roles.
💡 Found a typo or mistake? Click "Edit this page" to suggest a correction. Your feedback is greatly appreciated!