Roadmap › Custom Controls & Reusable UI Components in .NET — Web Forms to Blazor › Module: MVC and ASP.NET Core Components
Lessons in this course (9)
6. ASP.NET Core: view components vs partial views
Intermediate★ Must knowLesson 6 of 9
A view component is a mini-controller + view for a reusable widget that needs its own data and logic (replaces MVC 5 child actions).
csharp
public sealed class CartSummaryViewComponent(ICartService carts) : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync(int maxItems = 3)
{
var cart = await carts.GetForUserAsync(UserClaimsPrincipal);
return View(cart.Take(maxItems)); // Views/Shared/Components/CartSummary/Default.cshtml
}
}cshtml
@await Component.InvokeAsync("CartSummary", new { maxItems = 5 })
<vc:cart-summary max-items="5"></vc:cart-summary> @* tag-helper syntax *@| Partial view | View component | Tag helper | |
|---|---|---|---|
| Data | Passed in by the parent | Loads its own (DI, async) | Attributes |
| Logic | Minimal | Yes (class with DI) | Rendering logic |
| Typical use | Repeated markup (product card) | Widgets: cart summary, menu, recent posts | Element/attribute enhancement |
| Can be called from a controller | PartialView() | ViewComponent() result | — |
Razor Class Library (RCL): put views, view components, tag helpers, Razor Pages and static assets (wwwroot → _content/LibName/...) in a class library and reference it (or ship as NuGet) to reuse UI across apps.