ASP.NET Core MVC Views

Learn how to use views to render HTML output in ASP.NET Core MVC applications.

Introduction to Views

Views are the components in an ASP.NET Core MVC application responsible for rendering the user interface. They typically produce HTML, but can also generate other formats like JSON or XML. Views are designed to be lightweight and focus solely on presentation.

In ASP.NET Core MVC, views are commonly implemented using the Razor view engine. Razor is a powerful and concise templating syntax that allows you to embed C# code within HTML markup.

Razor Syntax

Razor uses the @ symbol to denote C# code. Here are some common Razor constructs:

Embedding Expressions

To render the result of a C# expression, use @expression.

Example: C# Expression
<p>Current time: @DateTime.Now</p>
<p>User name: @Model.UserName</p>

Code Blocks

For more complex logic, use @{ ... } to define a code block.

Example: C# Code Block
@{
    var message = "Hello from Razor!";
    var year = DateTime.Now.Year;
}
<p>@message @year</p>

Control Flow Statements

You can use standard C# control flow statements like if, foreach, and switch.

Example: Control Flow
<ul>
    @if (Model.Items.Any())
    {
        foreach (var item in Model.Items)
        {
            <li>@item</li>
        }
    }
    else
    {
        <li>No items found.</li>
    }
</ul>

HTML Attributes

Attributes can be set using C# expressions.

Example: HTML Attributes
<img src="@Model.ImageUrl" alt="@Model.ImageAltText" class="@(Model.IsFeatured ? "featured" : "")" />

View Structure and Organization

Views are typically located in the Views folder of your ASP.NET Core MVC project. They are often organized into subfolders corresponding to their controllers.

Layouts

Layouts (_Layout.cshtml) define the overall structure of your application's pages, such as headers, footers, and navigation. They use the @RenderBody() directive to inject the content of individual views.

Example: _Layout.cshtml
<!DOCTYPE html>
<html>
<head>
    <title>@ViewData["Title"] - My App</title>
    <link rel="stylesheet" href="/css/site.css" />
</head>
<body>
    <header>
        <nav>Navigation links...</nav>
    </header>
    <main role="main">
        @RenderBody()
    </main>
    <footer>
        <p>© @DateTime.Now.Year - My App</p>
    </footer>
    @RenderSection("Scripts", required: false)
</body>
</html>

View Imports and Start Pages

_ViewImports.cshtml files allow you to define common namespaces and directives for all views within a directory. _ViewStart.cshtml is used to specify a layout for views.

Note: By default, _ViewImports.cshtml and _ViewStart.cshtml are applied recursively from the Views folder down to subfolders.

Partial Views

Partial views are reusable view components that can be rendered within other views. They are useful for breaking down complex UIs into smaller, manageable pieces.

Example: Rendering a Partial View
<-- In a parent view -->
@Html.Partial("_MyPartialView")
<-- Or using the Tag Helper -->
<partial name="_MyPartialView" />

Strongly-Typed Views

Strongly-typed views are bound to a specific model type. This provides compile-time checking and IntelliSense support for model properties.

Use the @model directive at the top of your view to declare its type.

Example: Strongly-Typed View
// Assume MyModel is defined elsewhere
@model MyProject.Models.MyModel

<h1>Welcome, @Model.UserDisplayName!</h1>
<p>Your email is: @Model.EmailAddress</p>

ViewData and ViewBag

While strongly-typed views are preferred, you can also pass data to views using the ViewData dictionary or the dynamic ViewBag object.

Example: ViewData and ViewBag
// In Controller
ViewData["Message"] = "Hello from ViewData!";
ViewBag.PageTitle = "ViewBag Example";

// In View
<p>@ViewData["Message"]</p>
<h2>@ViewBag.PageTitle</h2>

Tag Helpers

Tag Helpers are a modern way to create server-side HTML markup in ASP.NET Core. They allow you to use HTML-like tags to interact with your server-side code.

For example, the <input> tag helper can be used to bind form inputs to model properties.

Example: Input Tag Helper
<!-- Model: @model MyProject.Models.UserEditModel -->
<div class="form-group">
    <label asp-for="UserName"></label>
    <input asp-for="UserName" class="form-control" />
    <span asp-validation-for="UserName" class="text-danger"></span>
</div>

Explore the Tag Helpers documentation for a comprehensive list and usage.

Best Practices

  • Keep views focused on presentation logic. Move business logic to models or services.
  • Use strongly-typed views whenever possible.
  • Organize views into logical folders.
  • Leverage layouts for consistent page structure.
  • Use partial views for reusable UI components.
  • Employ Tag Helpers for cleaner and more declarative HTML markup.