ASP.NET Core MVC Intermediate

Partial views

A partial view is a reusable piece of Razor markup, such as a product card or an address block, that you render inside other views. This lesson shows how to create one, pass it a model and render it the right way.

Rendering a list with a partial view
  1. StartThe page view runsProducts/Index.cshtml loops over the products
  2. Step 2Partial is called<partial name="_ProductCard" model="product" /> for each item
  3. Step 3Partial is locatedViews/Products/_ProductCard.cshtml, then Views/Shared
  4. Step 4Partial rendersIt receives one Product as its model
  5. EndOutput is combinedEvery card is inserted into the page HTML

The idea in plain words

When the same chunk of markup appears in several places, copy-pasting it means fixing every copy later. A partial view is a .cshtml file you render from another view. By convention its name starts with an underscore, for example _ProductCard.cshtml, to show it is not a full page.

A partial view has no controller of its own. It simply receives a model from the view that renders it, or shares the parent view's model if none is passed. _ViewStart.cshtml does not run for partials, so they never get a layout.

Example

The partial Tag Helper is the recommended way to render a partial. It is asynchronous and reads like HTML.

Razor
@* Views/Shared/_ProductCard.cshtml *@
@model Product
<article class="card">
    <h3>@Model.Name</h3>
    <p>@Model.Price.ToString("C")</p>
</article>

@* Views/Products/Index.cshtml *@
@model IEnumerable<Product>
<h1>Products</h1>
@foreach (var product in Model)
{
    <partial name="_ProductCard" model="product" />
}

Partial view or view component?

Use a partial view when the markup only needs data the parent view already has. If the piece needs its own data access or logic, such as a shopping cart summary shown on every page, use a view component instead (next lesson). Actions can also return PartialView() to send just a fragment, which is handy for updating part of a page with JavaScript.

Common mistakes

  • Using the synchronous Html.Partial helper, which can cause deadlocks. Use the partial Tag Helper or Html.PartialAsync.
  • Loading data from a database inside a partial view. Pass the data in, or use a view component.
  • Passing the wrong model type, which throws an InvalidOperationException at run time.

Interview question

When would you use a partial view instead of a view component?

Use a partial view to reuse markup when the parent view already has the data, for example rendering a product card for each item in a list. Use a view component when the reusable piece needs its own logic or data access, such as a cart summary or a menu built from the database, because a view component has a class with dependency injection and an InvokeAsync method.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.