LESSON 3 OF 20

3. Razor View Engine, Layouts, and Reusable UI Components

Learn how to organize ASP.NET Core MVC interfaces with Razor syntax, layouts, partial views, and view components.

45 dk 31

Introduction

In the previous lesson, we examined the MVC project structure and followed a request from a Controller to a View. In this lesson, we will make the View layer more organized, consistent, and maintainable. Copying repeated HTML into every View may seem convenient at first, but a small change to a navigation menu, footer, or notification area can then require edits in many files.

ASP.NET Core MVC provides Razor View Engine, layouts, partial views, and view components to reduce this duplication. Razor lets us place C# expressions inside HTML. A layout defines the common page shell used by multiple pages. A partial view represents a simple, reusable UI fragment that receives its data from the parent View. A view component is appropriate when a UI fragment must execute server-side code before it is rendered.

In this lesson, we will place the pages of our sample application inside a shared content-management interface, create a reusable notification area, and build a data-driven latest-articles component.

What Is the Razor View Engine?

Razor is a templating syntax that combines HTML and C# in .cshtml files. Normal HTML in a Razor file becomes part of the response sent to the browser. The @ character usually switches from HTML to C#.

<h2>Welcome, @Model.DisplayName</h2>
<p>Today's date: @DateTime.Now.ToShortDateString()</p>

Implicit expressions such as @Model.DisplayName are useful for printing a value. For more complex expressions, use an explicit Razor expression with parentheses.

<p>Total: @(Model.Items.Count * 10) USD</p>

Use a code block when several lines of C# must run before or between pieces of markup.

@{
    var pageTitle = "Content Management";
    var isPreview = true;
}

<h2>@pageTitle</h2>
@if (isPreview)
{
    <p>This page is in preview mode.</p>
}

Razor HTML-encodes string expressions by default. This behavior helps prevent text supplied by users from being interpreted as HTML or JavaScript. Treat user input as untrusted and avoid Html.Raw unless you have verified that the content is safe and has been sanitized when necessary. Rendering untrusted input with Html.Raw can create a cross-site scripting vulnerability.

Creating a Shared Page Shell with a Layout

A layout defines the common HTML structure of several pages in one file. The document head, navigation, main content container, and footer are typical layout responsibilities. In an MVC application, the common location is Views/Shared/_Layout.cshtml.

The location where page-specific content is inserted is marked with RenderBody(). When a View is rendered, its output is placed into that position inside the layout.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - Content Management</title>
</head>
<body>
    <header>
        <nav>
            <a asp-controller="Home" asp-action="Index">Home</a>
            <a asp-controller="Articles" asp-action="Index">Articles</a>
        </nav>
    </header>

    <main>
        @RenderBody()
    </main>

    <footer>
        <p>&copy; @DateTime.UtcNow.Year Content Management</p>
    </footer>
</body>
</html>

The layout used by Views can be selected in Views/_ViewStart.cshtml. This file is applied while Views beneath that folder are prepared.

@{
    Layout = "_Layout";
}

The extension is not required in the layout name. If the administration area and public pages need different navigation or page structures, create separate layouts and select the appropriate one for each area or View.

Using Sections in a Layout

Some pages need to add page-specific metadata, styles, or other content to a region defined by the layout. Use RenderSection for this purpose.

<head>
    <title>@ViewData["Title"]</title>
    @RenderSection("HeadContent", required: false)
</head>

A View can define that section as follows:

@section HeadContent {
    <meta name="description" content="Article list" />
}

Because required: false is used, Views do not have to define the section. If a required section is missing, rendering fails. Use sections to control well-known regions of a layout. For small, independent UI fragments, a partial view is usually a better choice.

Reusable HTML with Partial Views

A partial view is a small .cshtml file rendered by another View or by a layout. Partial view filenames commonly begin with an underscore, such as Views/Shared/_Alert.cshtml. Partial views work well for alert messages, user summaries, article cards, and other markup fragments that display data supplied by the calling View.

First, define a strongly typed model:

namespace ContentManager.ViewModels;

public class AlertViewModel
{
    public string Message { get; set; } = string.Empty;
    public string Level { get; set; } = "info";
}

Now create Views/Shared/_Alert.cshtml:

@model ContentManager.ViewModels.AlertViewModel

<div class="alert alert-@Model.Level" role="alert">
    @Model.Message
</div>

Render the partial with the Partial Tag Helper:

<partial name="_Alert" model="Model.Alert" />

An asynchronous HTML Helper is another option:

@await Html.PartialAsync("_Alert", Model.Alert)

The asynchronous approaches are preferred. Synchronous Html.Partial calls can introduce unnecessary blocking and may cause problems in some scenarios. A partial view does not run as a complete page and does not apply its own layout; it contributes markup to the output of the calling View.

Passing Data to a Partial View

Although ViewData can be used to pass values to a partial view, strongly typed models are generally safer for important UI components. The compiler can check property names, and the IDE can provide completion and refactoring support.

public class DashboardViewModel
{
    public string UserName { get; set; } = string.Empty;
    public AlertViewModel? Alert { get; set; }
}

Prepare the model in the Controller:

public IActionResult Index()
{
    var model = new DashboardViewModel
    {
        UserName = "Ayşe",
        Alert = new AlertViewModel
        {
            Message = "You have new drafts.",
            Level = "warning"
        }
    };

    return View(model);
}

Check for null before rendering the partial:

@if (Model.Alert is not null)
{
    <partial name="_Alert" model="Model.Alert" />
}

When Should You Use a View Component?

A partial view is ideal when it displays data that has already been prepared by the parent View or Controller. If the fragment must query a database, call a service, or perform server-side work before rendering, a view component is usually a better fit. Examples include the most-read articles, a shopping cart, and recent notifications.

Let us create a component that displays the latest articles. Add the component class to the ViewComponents folder:

using Microsoft.AspNetCore.Mvc;

public class LatestArticlesViewComponent : ViewComponent
{
    private readonly IArticleRepository _repository;

    public LatestArticlesViewComponent(IArticleRepository repository)
    {
        _repository = repository;
    }

    public async Task<IViewComponentResult> InvokeAsync(int count = 5)
    {
        var articles = await _repository.GetLatestAsync(count);
        return View(articles);
    }
}

The component receives its repository through dependency injection. It returns a View. The default View path is Views/Shared/Components/LatestArticles/Default.cshtml.

@model IReadOnlyList<ArticleListItemViewModel>

<aside>
    <h3>Latest Articles</h3>
    <ul>
    @foreach (var article in Model)
    {
        <li>
            <a asp-controller="Articles"
               asp-action="Details"
               asp-route-id="@article.Id">
                @article.Title
            </a>
        </li>
    }
    </ul>
</aside>

Invoke the component from a layout or regular View:

<vc:latest-articles count="5" />

This keeps layout-specific data retrieval out of ordinary Controllers. The view component owns the preparation and rendering of its own small UI area. However, do not place all business rules inside the component; move complex application logic into services.

Comparing Layouts, Partial Views, and View Components

StructurePrimary purposeData or code needs
LayoutDefine the shared page shellOverall structure shared by pages
Partial viewRender simple reusable markupUsually a model supplied by the caller
View componentRender a component that prepares its own dataServer-side code, services, or database access

A useful rule is: use a layout for the page skeleton, a partial view for formatting an existing model, and a view component when the UI fragment must collect or prepare data before rendering.

Implementation Steps

  1. Open Views/Shared/_Layout.cshtml and organize the shared document head, navigation, RenderBody(), and footer.

  2. Confirm that Views/_ViewStart.cshtml selects the _Layout layout.

  3. Create the AlertViewModel class and the Views/Shared/_Alert.cshtml partial view.

  4. Add an Alert property to a View Model and send a sample alert from the Controller.

  5. Render the alert with <partial name="_Alert" model="Model.Alert" />.

  6. Create a LatestArticlesViewComponent that uses a repository or service, and place its default View in the expected folder.

  7. Invoke it in the layout with <vc:latest-articles count="5" /> and verify that it appears consistently on multiple pages.

Common Mistakes

  • Using the wrong folder: A missing or incorrectly named partial or view-component View causes a “view not found” error. Check the path and casing.
  • Trying to apply a layout inside a partial: A partial is not a complete page. Select layouts from a normal View or _ViewStart.cshtml.
  • Putting database code in a View: Views should focus on presentation. Put data access in a Controller, service, or view component.
  • Forgetting the model declaration: Without an @model directive, type mismatches and runtime errors are more likely.
  • Rendering unsafe HTML as raw output: Passing user input directly to Html.Raw can create an XSS vulnerability.
  • Defining a section inside a partial: A section defined by a partial view is not available to its parent View.

Short Practice Exercise

Add a reusable “Recent Activities” area to the dashboard of your application.

  1. Create a RecentActivityViewModel containing an activity description, date, and URL.

  2. Create Views/Shared/_RecentActivities.cshtml and render the activities inside an unordered list.

  3. Add the activity collection to the Dashboard View Model and invoke the partial with the Partial Tag Helper.

  4. Verify that the same partial works on a second page when it receives the correct model.

  5. As a second stage, create a RecentActivitiesViewComponent that loads the data from a repository and replace the partial with the component.

Conclusion

In this lesson, you learned how Razor combines HTML and C#, how layouts provide a shared page structure, how partial views support simple reusable UI fragments, and how view components handle UI areas that need server-side data preparation.

A well-designed View layer avoids repeating the same markup in every page. The layout owns the page skeleton, the partial view owns small model-based fragments, and the view component owns fragments that must gather or prepare data. We will use this organized View structure in the next lessons when we begin working with forms and model binding.

Sources