ASP.NET Core MVC Views
On this page
Introduction to Views
Views in ASP.NET Core MVC are responsible for rendering the user interface (UI). They receive data from the controller (typically via a view model) and present it to the user in a formatted way. Views are typically written using the Razor view engine, which allows embedding C# code within HTML.
A well-structured application separates concerns, and views handle the presentation layer, keeping business logic and data access separate in models and controllers respectively.
Razor Syntax
Razor is a templating syntax for HTML that enables you to embed server-side code (C#) within your HTML markup. It uses the @
symbol to denote code expressions or statements.
Basic Razor Example
<h1>Welcome, @Model.UserName!</h1>
<p>Your role is: @(Model.IsAdmin ? "Administrator" : "User")</p>
<ul>
@foreach (var item in Model.Items)
{
<li>@item.Name</li>
}
</ul>
Key Razor elements include:
@variableName
: Renders the value of a variable or property.@(expression)
: Renders the result of a C# expression.@{ statement; statement; }
: Renders a block of C# statements.@if
,@foreach
,@using
: Control flow statements.
View Models
View models are Plain Old C# Objects (POCOs) that are specifically designed to hold the data required by a particular view. Controllers pass instances of view models to the views. This ensures that the view only receives the data it needs, promoting a clear separation of concerns and making views easier to test and maintain.
Example View Model
public class ProductViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public bool IsAvailable { get; set; }
}
In the view, you can strongly type the view to this model using @model ProductViewModel
at the top of the `.cshtml` file.
Layout Pages
Layout pages provide a consistent structure and branding across multiple views. They typically contain elements like headers, footers, navigation, and a placeholder for the content of the individual view. This avoids repetition and promotes a unified user experience.
Layouts are defined in files like `_Layout.cshtml` within the `Views/Shared` folder. The <partial name="_ValidationScriptsPartial" />
tag helper is often used to include client-side validation scripts.
Example _Layout.cshtml Snippet
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - My App</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
</head>
<body>
<header>
<nav>...</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody() <!-- Placeholder for view content -->
</main>
</div>
<footer>
<div class="container">
© 2023 - My App
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
@RenderSection("Scripts", required: false)
</body>
</html>
Individual views can specify their layout using @{ Layout = "~/Views/Shared/_Layout.cshtml"; }
or by convention if the layout file is named `_Layout.cshtml`.
Partial Views
Partial views are reusable view components that can be rendered within other views. They are useful for breaking down complex views into smaller, manageable, and reusable pieces. For example, a navigation bar or a product card can be implemented as a partial view.
You can render a partial view using the <partial name="..." />
tag helper or the Html.Partial()
helper method.
Rendering a Partial View
<!-- In your main view -->
<h2>Product Details</h2>
<partial name="_ProductInfo" model="Model" />
<!-- _ProductInfo.cshtml -->
<div>
<h3>@Model.Name</h3>
<p>Price: @Model.Price.ToString("C")</p>
</div>
View Components
View components are a special type of partial view that are executed on the server and can contain their own logic. They are ideal for building reusable UI elements that require data fetching or complex processing, such as a shopping cart summary or a user profile widget.
View components consist of a class with a InvokeAsync
method and a Razor view.
Invoking a View Component
<!-- In your view -->
<vc:shopping-cart summary="cartSummary" />
<!-- ShoppingCartViewComponent.cs -->
public class ShoppingCartViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync(string summary)
{
// Fetch cart data...
var cartData = await _cartService.GetCartDataAsync();
return View(cartData);
}
}
<!-- Views/Shared/Components/ShoppingCart/Default.cshtml -->
@model CartData
<div>
Items: @Model.ItemCount
</div>
Tag Helpers
Tag helpers allow you to write server-side code using HTML-like tags, making your Razor views feel more like static HTML. They transform HTML elements into Razor code during the rendering process. ASP.NET Core provides a rich set of built-in tag helpers for common tasks like forms, inputs, links, and more.
Using Form and Input Tag Helpers
<form asp-controller="Products" asp-action="Create" method="post">
<div class="form-group">
<label asp-for="Name"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
Key tag helpers include:
<form asp-action="..." asp-controller="...">
: For form submission.<input asp-for="...">
: Binds input fields to model properties.<label asp-for="...">
: Generates a label for a model property.<a asp-action="..." asp-controller="...">
: Generates links.