ASP.NET Core MVC Interview Question #21

What is a View Component in ASP.NET Core MVC?

MVC Fundamentals, Controllers, Views & Routing Junior Beginner

Quick Interview Answer

A View Component is a reusable UI component that combines server-side C# logic with a Razor view. It is useful when a portion of a page needs its own data retrieval or processing, such as a shopping cart summary, navigation menu, or featured-products widget.

Detailed Explanation

A View Component is a reusable UI component that combines server-side C# logic with a Razor view. It is useful when a portion of a page needs its own data retrieval or processing, such as a shopping cart summary, navigation menu, or featured-products widget.

Unlike controller actions, View Components are not directly selected through MVC routing and do not handle HTTP requests as endpoints. They are invoked from views or other rendering code.

Code Example

public class CartSummaryViewComponent : ViewComponent
{
    public IViewComponentResult Invoke()
    {
        return View(new CartSummaryViewModel());
    }
}

// Razor:
// @await Component.InvokeAsync("CartSummary")