AspNetCore.Docs/aspnetcore/mvc/views/partial.md

10 KiB

title author description ms.author ms.custom ms.date uid
Partial views in ASP.NET Core ardalis Learn how a partial view is a view that's rendered within another view and when they should be used in ASP.NET Core apps. riande mvc 07/06/2018 mvc/views/partial

Partial views in ASP.NET Core

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

ASP.NET Core MVC supports partial views, which are useful for sharing 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:

[!code-cshtml]

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.

[!TIP] Follow the Don't Repeat Yourself Principle in your views.

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.

::: moniker range=">= aspnetcore-2.1"

Partial Tag Helper

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

[!code-cshtml]

For more information, see xref:mvc/views/tag-helpers/builtin-th/partial-tag-helper.

::: moniker-end

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 @:

[!code-cshtml]

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:

[!code-cshtml]

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.

::: moniker range=">= aspnetcore-2.1"

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.

::: moniker-end

Partial view discovery

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

::: moniker range=">= aspnetcore-2.1"

// 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.

::: moniker-end

// 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:

[!code-cshtml]

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.

[!code-cshtml]

Views/Shared/_AuthorPartial:

[!code-cshtml]

The _ArticleSection partial:

[!code-cshtml]

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

partial view output

Additional resources

::: moniker range=">= aspnetcore-2.1"

::: moniker-end

::: moniker range="<= aspnetcore-2.0"

::: moniker-end