A View Component is a professional UI module that combines its own C# logic (a class) and its own Razor View. It is the gold standard alternative to Partial Views when you need logic that is **Independent** of the parent page.
We use them for any part of a layout that needs data from a database, but should not bloat the Controller. For example, a "Latest News Ticker" that appears on 50 different pages—instead of repeating the News logic in every Controller, you build it once as a **ViewComponent**.
A user adds an item to their cart. Every page on your site needs to show the "Cart Item Count (5)". Instead of passing this count from every action method, you build a CartSummaryViewComponent that fetches the session/DB count independently. No controller changes needed!
// The Component Class
public class CartSummaryViewComponent : ViewComponent {
public async Task InvokeAsync() {
var count = await _cartService.GetCount();
return View(count);
}
}
Total SoC (Separation of Concerns), reusable globally, and allows for cleaner, focused layouts.
Slightly more boilerplate code than a simple Partial View.
Performance: Use Async ViewComponents. They allow your high-traffic dashboard to start rendering content immediately while your dynamic widgets (e.g. news/cart) fetch their data asynchronously in the background. Security: Because ViewComponents don't have endpoints (they are called internally), they are naturally safer from direct web-based attacks.
Interview Question: "Why would you choose a ViewComponent over a Partial View?"
Architect Answer: "A Partial View is better for **Stateless** UI fragments where the Controller provides all the data. A **ViewComponent** is Mandatory for **Stateful** UI fragments where the component needs its own logic and database services, without polluting the parent controller with unnecessary dependencies. For a 12-year architect, this is the pillar of **Clean Layout Architecture**."