What is a View Component, and when do you use one instead of a partial view?
Quick Answer
A View Component is a mini-controller-plus-view for a self-contained UI widget that needs its own logic and data — a cart summary, a navigation menu, a “recently viewed” list. It has an InvokeAsync method with dependency injection, and you render it with <vc:cart-summary />. A partial view has no logic and uses the parent's model.
A View Component is for a reusable piece of UI that has its own logic — a shopping cart summary in the header, a category menu, a “top products” block. It's essentially a small controller with a view: an InvokeAsync method that can use DI to fetch its own data, and a Razor view. You drop it into a page with a tag helper. The difference from a partial view is that a partial has no logic and renders using whatever model the parent hands it. View Components replaced child actions from MVC 5.
- Class:
public class CartSummaryViewComponent : ViewComponent { public async Task<IViewComponentResult> InvokeAsync() { var cart = await _cartService.GetAsync(); return View(cart); } }. - View lives at
Views/Shared/Components/CartSummary/Default.cshtml. - Not reachable as a URL, unlike an action.
- Replaced the MVC 5
Html.Action/ child-action approach.