In this lesson, you will learn how to encapsulate complex UI logic into self-contained "View Components" that function as independent, reusable widgets.
Breaking the Monolithic View
Up until now, you have likely used Partial Views to split your code. While useful for simple markup, partials are often tightly coupled to the ViewData or Model of the parent page. This creates a dependency chain where a change in a parent page can inadvertently break a partial.
A View Component solves this by separating the logic from the view entirely. Think of it as a "mini-controller" for a specific section of your page. It doesn't rely on the parent controller’s state; instead, it manages its own data-fetching and rendering.
Anatomy of a View Component
A View Component consists of two parts: the C# class (logic) and the Razor file (markup). Here is a simple example of a "UserGreeting" component:
// GreetingViewComponent.cs
public class GreetingViewComponent : ViewComponent
{
public IViewComponentResult Invoke(string username)
{
var model = $"Hello, {username}! Welcome back.";
return View(model);
}
}
In the corresponding Default.cshtml file located in Views/Shared/Components/Greeting/, you simply accept the model:
@model string
<div class="alert alert-info">
@Model
</div>
Invocation
Because the component is independent, you can drop it anywhere in your application, regardless of what the parent page is doing:
@await Component.InvokeAsync("Greeting", new { username = "Alex" })
By decoupling the component, you ensure that the logic for generating the greeting is defined exactly once. If you decide to add a database lookup or extra formatting, you only modify the GreetingViewComponent class, and every page using this component updates instantly. This modular approach makes your UI library robust, testable, and significantly easier to maintain as your application grows.
Key Takeaway: View Components allow you to build autonomous UI fragments that encapsulate their own logic, data requirements, and rendering, preventing the "spaghetti code" that occurs when views become overly dependent on parent page state.