Partial Views & View Components
Partial = dumb HTML chunk. View Component = mini-controller with logic.
60-Second Version: Partial View = copy-paste HTML with
@model. View Component = reusable widget with its own C# code + DB calls. Use Partial for display. Use Component for logic.1. Partial Views: Reusable HTML
File: Views/Shared/_ProductCard.cshtml
@model ProductListViewModel
<div class="card">
<img src="@Model.ImageUrl" class="card-img-top">
<div class="card-body">
<h5>@Model.Name</h5>
<p>$@Model.SellPrice</p>
<a asp-action="Details" asp-route-id="@Model.Id">View</a>
</div>
</div>
Use it:
@model List<ProductListViewModel>
<div class="row">
@foreach (var product in Model)
{
<div class="col-4">
<partial name="_ProductCard" model="product" />
</div>
}
</div>
Rule: Partial has no controller. Parent passes all data via model. Name starts with _ by convention.
2. View Components: Reusable Logic
Problem: Show "Cart Items: 3" in Layout. Layout has no model. Partial can't call DB.
Solution: View Component = mini-controller.
File: ViewComponents/CartSummaryViewComponent.cs
public class CartSummaryViewComponent : ViewComponent
{
private readonly AppDbContext _db;
public CartSummaryViewComponent(AppDbContext db) { _db = db; }
public async Task<IViewComponentResult> InvokeAsync()
{
var userId = User.Identity.Name;
var count = await _db.CartItems
.Where(c => c.UserId == userId)
.SumAsync(c => c.Quantity);
return View(count); // Looks for Views/Shared/Components/CartSummary/Default.cshtml
}
}
View: Views/Shared/Components/CartSummary/Default.cshtml
@model int
<span class="badge bg-primary">Cart: @Model</span>
Use anywhere: <vc:cart-summary></vc:cart-summary> or @await Component.InvokeAsync("CartSummary")
3. Partial vs Component: When to Use
| Partial View | View Component | |
|---|---|---|
| Has C# logic? | No | Yes, own class |
| Calls DB? | No | Yes, via DI |
| Async? | No | Yes, InvokeAsync |
| Use case | Product card, form fields | Cart badge, recent posts, login widget |
Beginner Trap: Anil puts DB call in Partial View
@inject AppDbContext db. Works but violates MVC. Partials = display only. If you need data, parent passes it or use View Component.
Quick Check ๐ง
Next: Tag Helpers - Clean HTML syntax for ASP.NET features.
No comments yet. Be the first to share your thoughts!