Section 3 of 6
Razor Syntax
🎯 What You'll Learn
- Razor basics
- Expressions and code blocks
- Control structures
- HTML helpers
- Razor directives
- Comments
What is Razor?
Razor is a markup syntax for embedding C# code into HTML. It uses the
@ symbol to transition from HTML to C#.
Razor Expressions
Inline Expressions
Output C# Values
HTML
@model Product
<h1>@Model.Name</h1>
<p>Price: $@Model.Price</p>
<p>Total: $@(Model.Price * Model.Quantity)</p>
Explicit Expressions
Use Parentheses for Complex Expressions
HTML
<p>Email: @(user.FirstName + "@example.com")</p>
<p>Discount: @(Model.Price * 0.1)</p>
Encoding
HTML Encoding (Default)
HTML
<!-- Automatically HTML-encoded -->
<p>@Model.Description</p>
<!-- Raw HTML (use with caution!) -->
<p>@Html.Raw(Model.HtmlContent)</p>
Code Blocks
Multi-Line C# Code
HTML
@{
var total = Model.Price * Model.Quantity;
var discount = total * 0.1m;
var finalPrice = total - discount;
}
<p>Total: $@total</p>
<p>Discount: $@discount</p>
<p>Final Price: $@finalPrice</p>
Control Structures
If Statements
Conditional Rendering
HTML
@if (Model.Quantity > 0)
{
<span class="badge badge-success">In Stock</span>
}
@else if (Model.Quantity == 0)
{
<span class="badge badge-warning">Out of Stock</span>
}
@else
{
<span class="badge badge-danger">Discontinued</span>
}
Foreach Loops
Iterate Over Collections
HTML
@model List<Product>
<ul>
@foreach (var product in Model)
{
<li>@product.Name - $@product.Price</li>
}
</ul>
For Loops
Index-Based Iteration
HTML
<table>
@for (int i = 0; i < Model.Count; i++)
{
<tr>
<td>@(i + 1)</td>
<td>@Model[i].Name</td>
</tr>
}
</table>
Switch Statements
Switch Expression
HTML
@switch (Model.Status)
{
case "Active":
<span class="badge badge-success">Active</span>
break;
case "Pending":
<span class="badge badge-warning">Pending</span>
break;
default:
<span class="badge badge-secondary">Unknown</span>
break;
}
Razor Directives
@model
Specify Model Type
HTML
@model Product
@model List<Product>
@model IEnumerable<Product>
@using
Import Namespaces
HTML
@using InvenTrack.Models
@using System.Linq
<p>@DateTime.Now</p>
@inject
Dependency Injection in Views
HTML
@inject IConfiguration Configuration
<p>App Name: @Configuration["AppName"]</p>
@section
Define Content Sections
HTML
@section Scripts {
<script src="~/js/products.js"></script>
}
Comments
Razor Comments
HTML
@* This is a Razor comment (not sent to browser) *@
<!-- This is an HTML comment (sent to browser) -->
@{
// This is a C# comment
/* Multi-line
C# comment */
}
HTML Helpers
Form Helpers
Generate Form Elements
HTML
@model Product
@using (Html.BeginForm())
{
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name)
@Html.ValidationMessageFor(m => m.Name)
<button type="submit">Save</button>
}
Display Helpers
Display Model Properties
HTML
@Html.DisplayNameFor(m => m.Name)
@Html.DisplayFor(m => m.Name)
URL Helpers
Generate URLs
HTML
<a href="@Url.Action("Index", "Products")">Products</a>
<a href="@Url.Action("Details", new { id = 5 })">Details</a>
Complete InvenTrack Example
Views/Products/Index.cshtml
HTML
@model List<Product>
@{
ViewData["Title"] = "Products";
var totalValue = Model.Sum(p => p.Price * p.Quantity);
}
<div class="container">
<h1>InvenTrack Products</h1>
@if (TempData["Success"] != null)
{
<div class="alert alert-success">
@TempData["Success"]
</div>
}
<div class="mb-3">
<a asp-action="Create" class="btn btn-primary">Add New Product</a>
</div>
@if (Model.Count == 0)
{
<p>No products found.</p>
}
@else
{
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Category</th>
<th>Price</th>
<th>Quantity</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach (var product in Model)
{
<tr>
<td>@product.Name</td>
<td>@product.Category</td>
<td>$@product.Price.ToString("F2")</td>
<td>@product.Quantity</td>
<td>
@if (product.Quantity > 10)
{
<span class="badge bg-success">In Stock</span>
}
@else if (product.Quantity > 0)
{
<span class="badge bg-warning">Low Stock</span>
}
@else
{
<span class="badge bg-danger">Out of Stock</span>
}
</td>
<td>
<a asp-action="Details" asp-route-id="@product.Id" class="btn btn-sm btn-info">Details</a>
<a asp-action="Edit" asp-route-id="@product.Id" class="btn btn-sm btn-warning">Edit</a>
</td>
</tr>
}
</tbody>
</table>
<div class="alert alert-info">
Total Products: @Model.Count | Total Inventory Value: $@totalValue.ToString("F2")
</div>
}
</div>
@section Scripts {
<script>
console.log('Products page loaded');
</script>
}
Best Practices
- Use @ for C#: Transition from HTML to C# with @
- Parentheses for complex expressions: @(expression)
- HTML encoding: Razor automatically encodes output
- Avoid logic in views: Keep views simple, logic in controllers
- Use Tag Helpers: Prefer over HTML Helpers (next sections)
- Razor comments: Use @* *@ for comments not sent to browser
Key Takeaways
- Razor: Markup syntax for embedding C# in HTML
- @: Transition from HTML to C#
- @model: Specify view model type
- @if/@foreach: Control structures
- @{}: Code blocks
- @using/@inject: Import namespaces, inject services
- @section: Define content sections
- HTML Helpers: Generate form elements
🎯 Next Steps
You now understand Razor syntax! In the next section, we'll explore Layouts and Partials—how to create reusable page templates and shared UI components.