Partial views in ASP.NET Core

By Steve Smith, Maher JENDOUBI, Rick Anderson, and Scott Sauber

ASP.NET Core supports partial views. Partial views are used to share reusable parts of web pages across different views.

View or download sample code (how to download)

What are partial views

A partial view is a view that's rendered within another view. The HTML output generated by executing the partial view is rendered into the calling (or parent) view. Like views, partial views use the .cshtml file extension.

For example, the ASP.NET Core 2.1 Web Application project template includes a _CookieConsentPartial.cshtml partial view. The partial view is loaded from within _Layout.cshtml:

<partial name="_CookieConsentPartial" />

When to use partial views

Partial views are an effective way of breaking up large views into smaller components. They can reduce duplication of view content and allow view elements to be reused. Common layout elements should be specified in _Layout.cshtml. Non-layout reusable content can be encapsulated into partial views.

In a complex page composed of several logical pieces, it's helpful to work with each piece as its own partial view. Each piece of the page can be viewed in isolation from the rest of the page. The view for the page itself becomes simpler, since it only contains the overall page structure and calls to render the partial views.

ASP.NET Core MVC controllers have a PartialView method which is called from an action method. Razor Pages have no equivalent PartialView method on the PageModel.

Declare partial views

Partial views are created like a regular view—by creating a .cshtml file within the Views folder. There's no semantic difference between a partial view and a regular view; however, they're rendered differently. You can have a view that's returned directly from a controller's ViewResult, and the same view can be used as a partial view. The main difference between how a view and a partial view are rendered is that partial views don't run _ViewStart.cshtml. Regular views do run _ViewStart.cshtml. Learn more about _ViewStart.cshtml in Layout).

As a convention, partial view file names often begin with _. This naming convention isn't a requirement, but it helps to visually differentiate partial views from regular views.

Reference a partial view

Within a view page, there are several ways to render a partial view. The best practice is to use asynchronous rendering.

Partial Tag Helper

The Partial Tag Helper requires ASP.NET Core 2.1 or later. It renders asynchronously and uses an HTML-like syntax:

<partial name="_AuthorPartial" />

For more information, see Partial Tag Helper in ASP.NET Core.

Asynchronous HTML Helper

When using an HTML Helper, the best practice is to use PartialAsync. It returns an IHtmlContent type wrapped in a Task. The method is referenced by prefixing the call with @:

@await Html.PartialAsync("_AuthorPartial")

Alternatively, you can render a partial view with RenderPartialAsync. This method doesn't return a result. It streams the rendered output directly to the response. Because the method doesn't return a result, it must be called within a Razor code block:

@{
    await Html.RenderPartialAsync("_AuthorPartial");
}

Since it streams the result directly, RenderPartialAsync may perform better in some scenarios. However, it's recommended that you use PartialAsync.

Synchronous HTML Helper

Partial and RenderPartial are the synchronous equivalents of PartialAsync and RenderPartialAsync, respectively. Use of the synchronous equivalents isn't recommended because there are scenarios in which they deadlock. Future releases won't contain the synchronous methods.

Important

If your views need to execute code, use a view component instead of a partial view.

In ASP.NET Core 2.1 or later, calling Partial or RenderPartial results in an analyzer warning. For example, usage of Partial yields the following warning message:

Use of IHtmlHelper.Partial may result in application deadlocks. Consider using <partial> Tag Helper or IHtmlHelper.PartialAsync.

Replace calls to @Html.Partial with @await Html.PartialAsync or the Partial Tag Helper. For more information on Partial Tag Helper migration, see Migrate from an HTML Helper.

Partial view discovery

When referencing a partial view, you can refer to its location in several ways. For example:

// Uses a view in current folder with this name.
// If none is found, searches the Shared folder.
<partial name="_ViewName" />

// A view with this name must be in the same folder
<partial name="_ViewName.cshtml" />

// Locate the view based on the app root.
// Paths that start with "/" or "~/" refer to the app root.
<partial name="~/Views/Folder/_ViewName.cshtml" />
<partial name="/Views/Folder/_ViewName.cshtml" />

// Locate the view using a relative path
<partial name="../Account/_LoginPartial.cshtml" />

The preceding example uses the Partial Tag Helper, which requires ASP.NET Core 2.1 or later. The following example uses asynchronous HTML Helpers to accomplish the same task.

// Uses a view in current folder with this name.
// If none is found, searches the Shared folder.
@await Html.PartialAsync("_ViewName")

// A view with this name must be in the same folder
@await Html.PartialAsync("_ViewName.cshtml")

// Locate the view based on the app root.
// Paths that start with "/" or "~/" refer to the app root.
@await Html.PartialAsync("~/Views/Folder/_ViewName.cshtml")
@await Html.PartialAsync("/Views/Folder/_ViewName.cshtml")

// Locate the view using a relative path
@await Html.PartialAsync("../Account/_LoginPartial.cshtml")

You can have different partial views with the same file name in different view folders. When referencing the views by name (without a file extension), views in each folder use the partial view in the same folder with them. You can also specify a default partial view to use, placing it in the Shared folder. The shared partial view is used by any views that don't have their own version of the partial view. You can have a default partial view (in Shared), which is overridden by a partial view with the same name in the same folder as the parent view.

Partial views can be chained—a partial view can call another partial view (as long as you don't create a loop). Within each view or partial view, relative paths are always relative to that view, not to the root or parent view.

Note

A Razor section defined in a partial view is invisible to parents views. The section is only visible to the partial view in which it's defined.

Access data from partial views

When a partial view is instantiated, it gets a copy of the parent view's ViewData dictionary. Updates made to the data within the partial view aren't persisted to the parent view. ViewData changes in a partial view are lost when the partial view returns.

You can pass an instance of ViewDataDictionary to the partial view:

@await Html.PartialAsync("_PartialName", customViewData)

You can pass a model into a partial view. The model can be the page's view model or a custom object. You can pass a model to PartialAsync or RenderPartialAsync:

@await Html.PartialAsync("_PartialName", viewModel)

You can pass an instance of ViewDataDictionary and a view model to a partial view:

@await Html.PartialAsync("_ArticleSection", section,
                         new ViewDataDictionary(this.ViewData)
                         {
                             { "index", index }
                         })

The following markup shows the Views/Articles/Read.cshtml view, which contains two partial views. The second partial view passes in a model and ViewData to the partial view. Use the highlighted ViewDataDictionary constructor overload to pass a new ViewData dictionary while retaining the existing ViewData dictionary.

@model PartialViewsSample.ViewModels.Article

<h2>@Model.Title</h2>
@*Pass the author's name to Views\Shared\_AuthorPartial.cshtml*@
@await Html.PartialAsync("_AuthorPartial", Model.AuthorName)
@Model.PublicationDate

@*Loop over the Sections and pass in a section and additional ViewData
    to the strongly typed Views\Articles\_ArticleSection.cshtml partial view.*@
@{
    var index = 0;

    @foreach (var section in Model.Sections)
    {
        @await Html.PartialAsync("_ArticleSection", section,
                                 new ViewDataDictionary(this.ViewData)
                                 {
                                     { "index", index }
                                 })

        index++;
    }
}

Views/Shared/_AuthorPartial:

@model string
<div>
    <h3>@Model</h3>
    This partial view came from /Views/Shared/_AuthorPartial.cshtml.<br />
</div>

The _ArticleSection partial:

@using PartialViewsSample.ViewModels
@model ArticleSection

<h3>@Model.Title Index: @ViewData["index"]</h3>
<div>
    @Model.Content
</div>

At runtime, the partials are rendered into the parent view, which itself is rendered within the shared _Layout.cshtml.

partial view output

Additional resources