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 viewView componentTag helper
DataPassed in by the parentLoads its own (DI, async)Attributes
LogicMinimalYes (class with DI)Rendering logic
Typical useRepeated markup (product card)Widgets: cart summary, menu, recent postsElement/attribute enhancement
Can be called from a controllerPartialView()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.