ASP.NET Core MVC Views

This tutorial guides you through understanding and utilizing Views in ASP.NET Core MVC applications. Views are responsible for rendering the user interface (UI) of your web application.

What are Views?

In the Model-View-Controller (MVC) pattern, Views are the components that present data to the user. They typically consist of HTML markup, along with server-side code that dynamically generates content. ASP.NET Core MVC supports several view engines, with Razor being the most common and recommended.

Razor is a view engine that allows you to embed C# code within HTML using a concise syntax.

The Razor View Engine

Razor (.cshtml files) blends HTML markup with C# code. You can embed C# expressions using the @ symbol.

For example, to display a string variable named Message:

<p>Hello, @Message!</p>

To execute C# statements or blocks:

@{
    var greeting = "Welcome";
    var name = "User";
}
<h1>@greeting, @name!</h1>

@if (DateTime.Now.DayOfWeek == DayOfWeek.Friday)
{
    <p>It's Friday! Have a great weekend!</p>
}

Razor Syntax Highlights

  • Expressions: @variableName or @(expression)
  • Code Blocks: @{ ... } for C# statements.
  • Control Flow: Use standard C# if, foreach, etc., within code blocks.
  • HTML Encoding: Razor automatically HTML-encodes output from expressions to prevent cross-site scripting (XSS) attacks. Use @Html.Raw(stringVariable) to render unencoded HTML.

View Structure

ASP.NET Core MVC organizes views in a specific folder structure, typically under a Views folder in your project's root. Each controller typically has a corresponding subfolder within Views (e.g., Views/Home for the HomeController). View files usually have a .cshtml extension.

A common view file might look like this:

@model MyWebApp.Models.ProductViewModel

<!DOCTYPE html>
<html>
<head>
    <title>@ViewData["Title"] - Product Details</title>
    <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
</head>
<body>
    <h1>@Model.ProductName</h1>
    <p>Price: $@Model.Price.ToString("C")</p>
    <p>Description: @Model.Description</p>

    <a href="@Url.Action("Index", "Products")">Back to Products</a>
</body>
</html>

Key elements in the example:

  • @model MyWebApp.Models.ProductViewModel: Specifies the type of model the view expects.
  • @ViewData["Title"]: Accesses data passed from the controller using ViewData.
  • ~/css/site.css: Uses the tag helper asp-append-version for cache-busting CSS files.
  • @Model.ProductName: Accesses properties of the strongly-typed model.
  • @Url.Action("Index", "Products"): Generates a URL for the Index action in the Products controller.

Tag Helpers

Tag Helpers allow you to write server-side code directly within your HTML tags using attributes. They are a powerful way to reduce the amount of C# code you need to embed in your Razor views.

Examples:

  • <label asp-for="PropertyName"></label>
  • <input asp-for="PropertyName" class="form-control" />
  • <a asp-controller="Home" asp-action="About">About Us</a>
Tag Helpers are a key feature for writing clean and maintainable Razor views.

View Imports and Shared Views

_ViewImports.cshtml

This file, typically located in the Views folder, allows you to specify default imports for all Razor views in your application. You can use it to import namespaces, define default models, and apply default tag helpers.

@using MyWebApp
@using MyWebApp.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

_ViewStart.cshtml

This file, also in the Views folder, defines a layout for all views. Any code in _ViewStart.cshtml is executed before each view.

@{
    Layout = "_Layout.cshtml";
}

_Layout.cshtml

The main layout file defines the overall structure of your application (e.g., header, footer, navigation). Other views render their content within the @RenderBody() directive in the layout.

Passing Data to Views

Data is passed from controllers to views using various mechanisms:

  • Strongly-typed Models: The most recommended approach. A model object is created, populated, and passed to the view.
  • ViewDataDictionary: A dictionary (ViewData) for passing arbitrary data.
  • ViewBag: A dynamic property (ViewBag) offering a more convenient way to access ViewData.

Example (Controller):

public IActionResult Index()
{
    var products = new List<Product> {
        new Product { Id = 1, Name = "Laptop", Price = 1200.00m },
        new Product { Id = 2, Name = "Keyboard", Price = 75.50m }
    };

    ViewData["Title"] = "Product List";
    ViewBag.Message = "Here are our featured products.";

    return View(products); // Passing a strongly-typed model
}

Example (View - corresponding to the above controller):

@model IEnumerable<MyWebApp.Models.Product>
@* Model is the list of products *@
@* ViewData["Title"] is "Product List" *@
@* ViewBag.Message is "Here are our featured products." *@

<h1>@ViewData["Title"]</h1>
<p>@ViewBag.Message</p>

<table class="table">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Price</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var product in Model)
        {
            <tr>
                <td>@product.Id</td>
                <td>@product.Name</td>
                <td>@product.Price.ToString("C")</td>
            </tr>
        }
    </tbody>
</table>

Next Steps

Continue learning about other aspects of ASP.NET Core MVC to build robust web applications. Explore topics like validation, asynchronous operations, and client-side integration.

Mastering Views is crucial for creating engaging and user-friendly web experiences with ASP.NET Core MVC.