Views and Razor Syntax
Level: Intermediate
- Razor
@prefix:@student.Nameoutputs value,@{ var x = 5; }executes C# code in HTML - Display expressions:
@Model.Name(simple),@Model.DateOfBirth.ToShortDateString()(with methods),@(Model.IsActive ? "Yes" : "No")(ternary) - Code blocks:
@{ int count = 0; while (count < 10) { ... } }for multi-line C# logic - Loops:
@foreach (var student in Model) { ... }iterates students,@for (int i = 0; i < 10; i++)traditional for loop - Conditionals:
@if (student.Status == "Active") { ... } else { ... }for branching logic - Tag helpers:
<input asp-for="Name">binds to model,<a asp-controller="Students" asp-action="Details" asp-route-id="@student.Id">generates links - Model declaration:
@model Studentor@model List<Student>at top of view file - Layout:
@{ Layout = "_Layout"; }uses shared layout template (header, nav, footer) - Sections:
@section Scripts { ... }defines placeholder content that layout can render - Partial views:
@Html.PartialAsync("_StudentCard", student)reusable component (card, list item, widget) - ViewData:
@ViewData["Title"]weakly-typed,@ViewBag.Messagedynamic access - School Management examples: Students list loop, detail page with nested exams, edit form with dropdowns
- Common mistakes: Logic in views (belongs in controller/service), N+1 queries in loops, forgetting @Model.
Razor Basics
Razor = C# mixed with HTML.
@ prefix = C# code.
<!-- Display value -->
<p>Name: @student.Name</p>
<!-- C# expression -->
<p>Class: @student.ClassName.ToUpper()</p>
<!-- Code block -->
@{
var status = student.Status == StudentStatus.Active ? "Active" : "Inactive";
}
<p>@status</p>
Model Declaration
@model Student
<h1>@Model.Name</h1>
<p>Roll: @Model.RollNumber</p>
Or list:
@model List<Student>
@foreach (var student in Model)
{
<p>@student.Name</p>
}
Or view model:
@model StudentViewModel
<h1>@Model.Student.Name</h1>
<p>Exams: @Model.Exams.Count</p>
Display Expressions
<!-- Simple output -->
@student.Name
<!-- With method -->
@student.DateOfBirth.ToShortDateString()
<!-- Ternary -->
@(student.Status == StudentStatus.Active ? "✓ Active" : "✗ Inactive")
<!-- Null coalescing -->
@(student.ParentName ?? "No parent info")
Loops
<!-- Foreach -->
@foreach (var student in Model)
{
<tr>
<td>@student.Name</td>
<td>@student.RollNumber</td>
</tr>
}
<!-- While -->
@{
int count = 0;
}
@while (count < 10)
{
<p>Count: @count</p>
count++;
}
<!-- For -->
@for (int i = 0; i < Model.Count; i++)
{
<p>@Model[i].Name</p>
}
Conditionals
@if (student.Status == StudentStatus.Active)
{
<span class="badge bg-success">Active</span>
}
else if (student.Status == StudentStatus.Inactive)
{
<span class="badge bg-warning">Inactive</span>
}
else
{
<span class="badge bg-secondary">Graduated</span>
}
Switch Statements
@switch (student.ClassName)
{
case "10-A":
<p>Class 10 Section A</p>
break;
case "10-B":
<p>Class 10 Section B</p>
break;
default:
<p>Other class</p>
break;
}
Display Templates
Format output without logic.
<!-- Display bool as Yes/No -->
@Html.DisplayFor(m => m.IsActive)
<!-- Display DateTime as short date -->
@Html.DisplayFor(m => m.CreatedAt)
<!-- Display enum as name -->
@Html.DisplayFor(m => m.Status)
Templates in Views/Shared/DisplayTemplates/ or EditorTemplates/
HTML Helpers
Generate HTML from model.
<!-- Textbox bound to property -->
@Html.TextBoxFor(m => m.Name)
<!-- Generates: <input type="text" name="Name" value="Ravi" /> -->
<!-- Dropdown -->
@Html.DropDownListFor(m => m.ClassName, Model.ClassOptions)
<!-- Checkbox -->
@Html.CheckBoxFor(m => m.IsActive)
<!-- Hidden field -->
@Html.HiddenFor(m => m.Id)
<!-- Display label -->
@Html.LabelFor(m => m.Name)
<!-- Validation message -->
@Html.ValidationMessageFor(m => m.Name)
Tag Helpers (Modern Alternative)
<!-- Textbox -->
<input asp-for="Name" class="form-control" />
<!-- Generates: <input type="text" name="Name" id="Name" class="form-control" value="..." />
<!-- Dropdown -->
<select asp-for="ClassName" asp-items="Model.ClassOptions"></select>
<!-- Checkbox -->
<input type="checkbox" asp-for="IsActive" />
<!-- Validation -->
<span asp-validation-for="Name" class="text-danger"></span>
<!-- Link -->
<a asp-controller="Students" asp-action="Details" asp-route-id="@student.Id">View</a>
<!-- Form -->
<form asp-controller="Students" asp-action="Create" method="post">
@Html.AntiForgeryToken()
</form>
Layouts
Shared HTML structure (header, nav, footer).
File: Views/Shared/_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<title>@ViewData["Title"] - SMS</title>
</head>
<body>
<header>
<nav><!-- Navigation --></nav>
</header>
<main>
@RenderBody()
</main>
@RenderSection("Scripts", required: false)
</body>
</html>
Use in view:
@{
ViewData["Title"] = "Students";
Layout = "_Layout";
}
<h1>Students List</h1>
<!-- Page content -->
Default layout: _Layout.cshtml in Shared folder.
Sections
Define placeholder content in layout.
<!-- Layout has -->
@RenderSection("Scripts", required: false)
<!-- View provides -->
@section Scripts {
<script>
console.log('Page-specific script');
</script>
}
Partial Views
Reusable HTML component.
File: Views/Shared/_StudentCard.cshtml
@model Student
<div class="card">
<div class="card-body">
<h5>@Model.Name</h5>
<p>Roll: @Model.RollNumber</p>
<p>Class: @Model.ClassName</p>
</div>
</div>
Use in view:
@foreach (var student in Model)
{
@Html.PartialAsync("_StudentCard", student)
}
<!-- Or with tag helper -->
<partial name="_StudentCard" model="student" />
ViewData and ViewBag
Pass data from controller to view.
// In controller
public IActionResult Index()
{
ViewData["Title"] = "Student List";
ViewBag.TotalCount = 150;
return View();
}
<!-- In view -->
<h1>@ViewData["Title"]</h1>
<p>Total: @ViewBag.TotalCount</p>
Prefer strongly-typed models over ViewData.
Key Takeaways
@prefix = Razor syntax@+ expression = output@{ }= code block- Loops, conditionals = standard C#
- Tag helpers = modern, type-safe HTML
- HTML helpers = older, less safe
- Layouts = shared structure
- Partials = reusable components
- Strongly-typed models = best practice
Keep logic out of views. Use view models and display templates instead.
Use ChatGPT, Claude, or Copilot to go deeper on Views and Razor Syntax. Try these prompts:
"What's the difference between ViewData and strongly-typed models?""When should I use tag helpers vs HTML helpers?""How do partials and layouts differ?""What is a view model?""Quiz me on Razor"
💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.