skip to content

In ASP.NET Core MVC, when would you build a view component instead of a partial view, and how do you write and invoke one?

level: middleimportance: must knowfreq 55%

answer

  1. logic and data of its own
  2. Invoke or InvokeAsync, exactly one
  3. Components/{Name}/Default.cshtml
  4. Component.InvokeAsync or a vc: element
  5. no model binding, no filters, no URL

basics

~20 s

Use a view component when a reusable widget needs its own logic or data, such as a basket summary on every page; a partial view only renders the model its caller passes. A view component is a class with InvokeAsync and its own view.

solid answer

~40 s

A **partial view** is just markup: it renders with whatever model and `ViewData` the calling view hands it (`<partial name="_BasketLine" model="line" />`) and has no code of its own. A **view component** is a class deriving from `ViewComponent` (or named `...ViewComponent`, or marked `[ViewComponent]`) with exactly one public `Invoke` or `InvokeAsync` method; it takes constructor-injected services, loads its own data and returns `View(model)`, which looks for `Views/{Controller}/Components/{Name}/Default.cshtml` and then `Views/Shared/Components/{Name}/Default.cshtml`. You invoke it with `@await Component.InvokeAsync("BasketSummary", new { maxLines = 3 })` or, after `@addTagHelper *, <your assembly>`, as `<vc:basket-summary max-lines="3"></vc:basket-summary>`. Its arguments come from the caller, not from model binding, filters do not run around it, and it has no URL of its own.

code

csharp · 14 lines
csharp
public class BasketSummaryViewComponent(IBasketService baskets) : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync(int maxLines = 3)
    {
        var basket = await baskets.GetForUserAsync(UserClaimsPrincipal);
        var model = new BasketSummaryModel(
            basket.Lines.Take(maxLines).ToList(),
            basket.Lines.Count,
            basket.Subtotal);

        // Views/Shared/Components/BasketSummary/Default.cshtml
        return View(model);
    }
}

go deeper

for a junior

Recall that a partial renders markup with the caller's model, while a view component is a class with InvokeAsync and a Default.cshtml view.

for a middle

Explain the discovery rules, the view search path, both invocation forms, and why arguments come from the caller instead of model binding.

for a senior

Decide where data loading belongs, keep layouts free of controller coupling, and expose a component through ViewComponent() for partial page refreshes.

for a principal

Set a team rule for partials versus view components versus Razor components so reusable UI does not split across three styles without reason.

## Two ways to reuse a piece of a page A garden-centre site shows a **basket summary** in the header of every page: item count, subtotal, a link to checkout. The pages are rendered by different controllers with unrelated models, so the question is where the basket data comes from. | | Partial view | View component | |---|---|---| | What it is | a `.cshtml` file | a C# class plus a `.cshtml` view | | Data | the model and `ViewData` its caller passes | whatever its own code loads | | Dependencies | none of its own | constructor injection | | Invoked with | `<partial name="..." />` | `Component.InvokeAsync(...)` or `<vc:...>` | | Good for | repeated markup over data you already have | a self-contained widget with logic | A **partial view** fits when the caller already holds the data: rendering each basket line on the basket page with `<partial name="_BasketLine" model="line" />`. Making every controller load basket data just so the layout's partial can render it couples unrelated actions to the basket; a **view component** owns that work instead. ## Writing one A class becomes a view component when it is public, non-abstract and either derives from `ViewComponent`, ends with the `ViewComponent` suffix, or carries `[ViewComponent]`. `[NonViewComponent]` opts a matching class out. - It must have **exactly one** public method named `Invoke` or `InvokeAsync`; none, both, or two overloads make MVC throw `InvalidOperationException` when it builds the component's descriptor. - `InvokeAsync` must return a `Task<T>`, normally `Task<IViewComponentResult>`; `Invoke` must return a value, normally `IViewComponentResult`. - `View(model)` renders a Razor view, `Content(string)` writes HTML-encoded text. - Constructor parameters are resolved from DI per invocation, and the base class exposes `HttpContext`, `User`, `ViewData`, `ModelState` and `TempData` of the current request. ## Where its view lives `View()` with no name looks for a view called `Default` under `Components/{Name}`, where `{Name}` is the class name without the `ViewComponent` suffix: 1. `Views/{Controller}/Components/BasketSummary/Default.cshtml`, so one controller can override it; 2. `Views/Shared/Components/BasketSummary/Default.cshtml`, the usual home; 3. in a Razor Pages app, `Pages/Shared/Components/BasketSummary/Default.cshtml`. `View("Compact", model)` picks `Components/BasketSummary/Compact.cshtml` instead. ## Invoking it From any view or layout: ```razor @await Component.InvokeAsync("BasketSummary", new { maxLines = 3 }) @* or, with @addTagHelper *, GardenCentre.Web in _ViewImports.cshtml *@ <vc:basket-summary max-lines="3"></vc:basket-summary> ``` - The anonymous object's property names must match `InvokeAsync` parameter names. - The `vc:` form turns the Pascal-case class and parameter names into kebab case (`BasketSummary` becomes `basket-summary`, `maxLines` becomes `max-lines`). - The `vc:` element needs the **app's own assembly** registered with `@addTagHelper`; the built-in `Microsoft.AspNetCore.Mvc.TagHelpers` line is not enough. ## What a view component is not - It does **not** take part in model binding: its arguments are whatever the caller passes. - MVC **filters** do not run around it; an action filter on the controller wraps the action, not the component. - It has **no route**. To refresh the basket summary with JavaScript, add a controller action that returns `ViewComponent("BasketSummary", new { maxLines = 3 })`. ## Lifetime and testing - MVC creates a **new instance for every invocation**, resolving constructor parameters from the request's services; `AddViewComponentsAsServices()` registers the components in DI themselves when you want the container to build them. - Because the component is a plain class, a unit test can construct it with a fake `IBasketService`, call `InvokeAsync`, cast the result to `ViewViewComponentResult` and assert on `ViewData.Model` and `ViewName`. - Keep `InvokeAsync` truly asynchronous for I/O. A layout invokes the component on every page, so a blocking call there costs every request. ## In an interview Strong answers state the deciding question (does the fragment need its own data or logic?), name the `InvokeAsync` plus `Default.cshtml` convention, and show both invocation forms. Weak answers describe a view component as "a partial with a model" or expect a URL for it.

  • How would you refresh only the basket summary after an AJAX add-to-basket call?
    A view component has no URL, so expose one: a controller action that returns `ViewComponent("BasketSummary", new { maxLines = 3 })`. It runs the same `InvokeAsync` and renders the same `Default.cshtml`, returning just that fragment, which the script swaps into the header.
  • Why does <vc:basket-summary> render as a literal unknown element in the browser?
    The `vc:` tag helpers are generated for view components in the app's assembly, and Razor only applies them when that assembly is registered: `@addTagHelper *, GardenCentre.Web` in `_ViewImports.cshtml`. The built-in `Microsoft.AspNetCore.Mvc.TagHelpers` line covers the framework's helpers only, so without the second line the element passes through untouched.
  • Do action filters on the controller run when a view component executes?
    No. Filters wrap the action that renders the page; a view component invoked from that page's view runs inside view rendering, with no filter pipeline of its own. Cross-cutting checks a component needs (for example whether the user is signed in) go in the component's own code.

  • A view component is reachable by URL like a controller action
  • View component arguments are model-bound from the query string
  • Action filters on the controller wrap every view component the page renders
  • A partial view should query the database so each page stays thin
  • A class may declare both Invoke and InvokeAsync and MVC picks one