skip to content

In ASP.NET Core MVC, when should a listings page use a partial view, how is the partial found, and what data does it receive?

level: middleimportance: should knowfreq 48%

answer

  1. reusable markup, no _ViewStart, no layout
  2. Html.PartialAsync / RenderPartialAsync
  3. sync Html.Partial: MVC1000 deadlock warning
  4. controller folder, then Shared
  5. copy of the parent's ViewData

basics

~20 s

Use a partial for markup repeated across views, such as a listing card. It is found like a view (controller folder, then Shared) and receives the model you pass plus a copy of the parent's ViewData, without _ViewStart or a layout.

solid answer

~50 s

A partial view is a `.cshtml` file, by convention named with a leading underscore like `_ListingCard.cshtml`, rendered inside another view. Render it with `@await Html.PartialAsync("_ListingCard", listing)`, or `await Html.RenderPartialAsync(...)` to write straight to the output, or the `<partial>` tag helper; avoid the synchronous `Html.Partial`, which the Web SDK's MVC1000 analyzer flags as a deadlock risk. A path (ending in `.cshtml`, or starting with `~` or `/`) is resolved relative to the calling view; a plain name goes through the normal view locations: `/Views/{controller}/`, `/Views/Shared/`, and `/Pages/Shared/` when Razor Pages are registered. The partial gets a **new** `ViewDataDictionary` copied from the parent with the model you passed, so its writes don't flow back. It runs without `_ViewStart` and therefore without a layout, which is also why `return PartialView("_ListingCard", listing)` suits AJAX fragments. If the markup needs its own data access or logic, a view component fits better.

code

razor · 14 lines
razor
@* Views/Shared/_ListingCard.cshtml *@
@model ListingCardViewModel
<article class="listing-card">
    <img src="@Model.PhotoUrl" alt="@Model.Address" />
    <h3>@Model.Price.ToString("C0")</h3>
    <p>@Model.Bedrooms bd · @Model.Bathrooms ba</p>
</article>

@* Views/Listings/Search.cshtml *@
@model SearchResultsViewModel
@foreach (var listing in Model.Listings)
{
    @await Html.PartialAsync("_ListingCard", listing)
}

go deeper

for a junior

Recall that a partial is a reusable .cshtml fragment rendered with Html.PartialAsync or the partial tag helper, usually named with a leading underscore.

for a middle

Explain the lookup order, the copied ViewData with the passed model, and why partials run without _ViewStart, layouts or sections.

for a senior

Remove synchronous Html.Partial calls, use PartialView for AJAX fragments, and move data-fetching fragments to view components.

for a principal

Decide how the UI is composed across partials, view components and Razor components so teams reuse markup without hidden data dependencies.

## What a partial is for On a real-estate site the same **listing card** (photo, price, bedrooms, a favourite button) appears on the search results, the agent's profile and the "similar homes" strip. Copying that markup into three views guarantees they drift apart. A **partial view** is a Razor file rendered inside another view's output, so the card is written once. Good candidates: - repeated fragments that render data they are **given** (cards, address blocks, pagination bars); - splitting a long view into readable pieces; - HTML fragments returned to JavaScript for in-place updates. If the fragment needs to **fetch** its own data ("three newest listings in this area"), a view component, which has a class with its own dependencies, is the better tool. ## Rendering a partial | API | Returns or writes | Notes | |---|---|---| | `@await Html.PartialAsync("_ListingCard", model)` | returns `IHtmlContent` | the usual HTML-helper form | | `@{ await Html.RenderPartialAsync("_ListingCard", model); }` | writes to the output | avoids an intermediate buffer | | `<partial name="_ListingCard" model="listing" />` | tag helper | asynchronous, the markup-friendly form | | `Html.Partial(...)`, `Html.RenderPartial(...)` | synchronous | flagged by **MVC1000**: "may result in application deadlocks" | | `return PartialView("_ListingCard", model);` | a `PartialViewResult` from a controller | renders only the partial | The synchronous helpers block a thread while the partial renders asynchronously underneath; the analyzer bundled with the Web SDK warns and suggests the tag helper or the `Async` method. ## How the partial is found `HtmlHelper` first calls the view engine's `GetView` with the calling view's path. A name ending in `.cshtml`, or starting with `~` or `/`, is resolved as a path (relative to the calling view, or app-relative). A plain name goes through `FindView` with the normal location formats: 1. `/Views/{controller}/_ListingCard.cshtml` 2. `/Views/Shared/_ListingCard.cshtml` 3. `/Pages/Shared/_ListingCard.cshtml` when Razor Pages are registered (Areas use the area formats first.) If nothing matches, MVC throws `InvalidOperationException`: "The partial view '_ListingCard' was not found. The following locations were searched:" with the paths tried. ## What data it receives The helper builds a **new** `ViewDataDictionary<object>` from the parent's `ViewData` (or from a `ViewDataDictionary` you pass) and sets its model: - `Html.PartialAsync("_ListingCard")` passes the parent's model; - `Html.PartialAsync("_ListingCard", listing)` passes `listing`; - `Html.PartialAsync("_ListingCard", listing, new ViewDataDictionary(ViewData) { ["Compact"] = true })` adds extra entries for this call. Because it is a copy, a value the partial writes to `ViewData` is invisible to the parent and to sibling partials. If the partial declares `@model ListingCardViewModel`, the model must be of that type or rendering fails. ## What a partial does not get - **No `_ViewStart`.** The engine collects `_ViewStart` files only for main pages, so `Layout` stays null and the partial renders bare. - **No sections.** A partial cannot define `@section Scripts` for the layout and cannot call `RenderSection`; sections belong to the main view and its immediate layout. Put a script the card needs in the page's `Scripts` section instead. ## Partial or not? | Need | Better tool | |---|---| | Same markup, data passed in | partial view | | Same markup, fetches its own data | view component | | Interactive UI with client-side state | a Razor component | | A whole page shell | layout | Partials are cheap but not free: the lookup is cached and the view is precompiled, so there is no file access or compilation per call, but each call allocates a `ViewDataDictionary`, a view instance and a `ViewContext`. For a results page of a few dozen cards that is negligible; for loops over hundreds of items, measure before and after. The bigger cost is indirection, so avoid partials that are used once and are only a few lines long. ## Returning a partial from a controller For a "load more listings" button, an action can render only the cards: ```csharp public async Task<IActionResult> MoreResults(string area, int page, CancellationToken ct) { var listings = await _search.PageAsync(area, page, ct); return PartialView("_ListingCards", listings); } ``` `PartialViewResult` uses the same lookup, runs no `_ViewStart` and no layout, and the JavaScript inserts the returned HTML into the page.

  • Why does Html.Partial produce a warning while Html.PartialAsync does not?
    Views render asynchronously, so the synchronous `Html.Partial` has to block on that work. The MVC1000 analyzer in the Web SDK warns that this may deadlock and suggests `Html.PartialAsync` or the `<partial>` tag helper, which await the rendering.
  • When would you choose a view component over a partial for the 'similar homes' strip?
    When the strip must load its own data, such as querying listings near the current one. A view component has a class with injected services and an `InvokeAsync` method that prepares the model, whereas a partial only renders what the calling view hands it.

  • A partial view gets the site layout because _ViewStart runs for it.
  • Changes a partial makes to ViewData are visible to the parent view afterwards.
  • Html.Partial and Html.PartialAsync are equally safe to use in views.
  • A partial can add a @section Scripts block that the layout renders.
  • Partial views must live in Views/Shared or they are never found.