MSDN Documentation

Microsoft Developer Network

ASP.NET Core Views

This document provides a comprehensive overview of how to use views in ASP.NET Core to render dynamic content for your web applications.

Introduction to Views

In ASP.NET Core MVC, views are responsible for presenting the application's data to the user. They are typically implemented using the Razor view engine, which allows you to embed server-side code within HTML markup.

Views work in conjunction with controllers and models to form the Model-View-Controller (MVC) architectural pattern. Controllers process incoming requests, interact with models to retrieve or manipulate data, and then select a view to render the response.

Razor Syntax

Razor is a templating language for .NET that uses the @ symbol to delineate server-side code from HTML. It's designed to be concise and easy to read.

Inline Expressions

You can embed C# expressions directly into your HTML using the @ symbol followed by the expression. The result of the expression is written to the output stream.


<p>The current time is: @DateTime.Now</p>
<p>User's name: @Model.UserName</p>
                    

Statements

For more complex logic, you can use the @ symbol followed by curly braces { } to enclose C# statements.


<ul>
@if (Model.Items.Count > 0)
{
    <foreach (var item in Model.Items)
    {
        <li>@item</li>
    }
}
else
{
    <li>No items available.</li>
}
</ul>
                    

Directives

Razor directives are used to import namespaces, set base classes, and control how the view is processed.

  • @using: Imports a namespace.
  • @model: Specifies the type of the model that the view expects.
  • @inject: Injects a service into the view.

@using System.Collections.Generic
@model MyWebApp.Models.ProductViewModel
@inject IConfiguration Configuration
                    

View Models

View models are C# classes that represent the data a specific view needs. They help decouple the view from the domain model and provide a focused data structure for presentation.

Typically, a controller action populates a view model and passes it to the view:


public class ProductViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public List<string> Features { get; set; }
}

// Controller Action
public IActionResult Details(int id)
{
    // ... fetch product data ...
    var viewModel = new ProductViewModel
    {
        Id = product.Id,
        Name = product.Name,
        Price = product.Price,
        Features = product.GetFeatures()
    };
    return View(viewModel);
}
                    

In the view, you'd access these properties via the @Model object.

Layout Pages

Layout pages define the overall structure and common elements of your application's views, such as headers, footers, and navigation bars. This promotes consistency and reduces redundancy.

A layout page typically contains an @RenderBody() method, which indicates where the content of a specific view will be rendered.


<!DOCTYPE html>
<html>
<head>
    <title>@ViewData["Title"] - My App</title>
    <link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
    <header>
        <nav>...</nav>
    </header>
    <main>
        <div class="container">
            @RenderBody()
        </div>
    </main>
    <footer>
        © 2023 My App
    </footer>
</body>
</html>
                    

Individual views can specify which layout to use or opt-out of layouts.

Partial Views

Partial views are Razor views that can be used to render a portion of a view. They are useful for reusing UI components or breaking down complex views into smaller, manageable parts.

You can render a partial view using the Html.Partial() or Html.RenderPartial() methods.


<div class="product-details">
    <h3>@Model.Name</h3>
    <p>Price: @Model.Price.ToString("C")</p>

    <!-- Render a partial view for the features -->
    @Html.Partial("_ProductFeatures", Model.Features)
</div>
                    

The _ProductFeatures.cshtml partial view would contain the markup to display the list of features.

View Inheritance

View inheritance allows you to create a base view with common elements and then have other views inherit from it. This is similar to layout pages but offers more flexibility in defining the structure of derived views.

Define a base view (e.g., _BaseView.cshtml) using the @inherits directive:


@inherits System.Web.Mvc.WebViewPage<MyWebApp.Models.BaseViewModel>

<h2>@Model.PageTitle</h2>
<div class="content">
    @RenderSection("MainContent", required: false)
</div>
                    

Then, in a derived view, specify the base view and define sections:


@inherits MyWebApp.Views._BaseView

@section MainContent {
    <p>This is the specific content for this page.</p>
    <p>Details: @Model.SpecificDetails</p>
}
                    

Tag Helpers

Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files. They allow you to write HTML-like syntax for server-side logic, making your Razor code more readable and maintainable.

ASP.NET Core includes many built-in Tag Helpers, such as <form>, <a>, and <img>.


<!-- Standard HTML -->
<a href="/products/index">View Products</a>

<!-- Using the Anchor Tag Helper -->
<a asp-controller="Products" asp-action="Index">View Products</a>

<!-- Using the Form Tag Helper -->
<form asp-controller="Account" asp-action="Login" method="post">
    <!-- form elements -->
    <button type="submit">Login</button>
</form>
                    

You can also create your own custom Tag Helpers.

HTML Helpers

HTML Helpers are C# methods that return HTML strings. While Tag Helpers are generally preferred in modern ASP.NET Core development for their HTML-like syntax, HTML Helpers are still widely used and supported.

Examples include Html.ActionLink() and Html.TextBoxFor().


<!-- Using Html.ActionLink -->
@Html.ActionLink("View Products", "Index", "Products")

<!-- Using Html.TextBoxFor with a ViewModel -->
<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>