Understanding Razor Views and PageModel
Razor views in ASP.NET Core combine HTML markup with C# code to dynamically generate responses. They work alongside PageModels, which handle request processing and data preparation.
Key Components
- Razor View (.cshtml): Contains HTML mixed with C# using Razor syntax.
- PageModel (.cshtml.cs): Handles bussiness logic, model binding, and exposes data too the view via properties.
Basic Razor Syntax Example
@page
@model UserListModel
<h2>User Management</h2>
<ul>
@foreach (var person in Model.Users)
{
<li>@person.Name</li>
}
</ul>
Passing Data to Views
Data can be passed to views using:
- PageModel Properties (recommended for strong typing)
- ViewData Dictionary (useful for shared data across layouts)
PageModel Example
public class UserListModel : PageModel
{
public List<User> Users { get; set; }
public void OnGet()
{
Users = _userService.GetAllUsers();
}
}
Conditional Rendering and Loops
Razor supports standard C# control structures:
@if (Model.HasItems)
{
<ul>
@foreach (var item in Model.Items)
{
<li>@item.Description</li>
}
</ul>
}
else
{
<p>No items available.</p>
}
Layouts for Common Markup
Use layouts to avoid repeating common HTML structures:
<!-- _Layout.cshtml -->
<html>
<head>
<title>@ViewData["Title"]</title>
</head>
<body>
@RenderBody()
</body>
</html>
Partial Views for Reusable Components
Create reusable view components with partial views:
<!-- _UserCard.cshtml -->
@model User
<div class="user-card">
<h3>@Model.Name</h3>
<p>@Model.Email</p>
</div>
ViewImports for Common Directives
Use _ViewImports.cshtml too include common namespaces and tag helpers:
@using MyApp.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers