Introduction
Large ShopNest sites repeat chrome — headers, footers, nav, cart widgets. Layouts wrap every page; partial views reuse HTML fragments; view components render reusable widgets with their own logic and data loading.
After this article you will
- Master @RenderBody() and @RenderSection() in layouts
- Choose between partial views and view components
- Build navigation and shopping cart widgets
- Use async partial rendering for performance
Prerequisites
- Article 7 — Views and Razor Syntax
- ShopNest.Web project from prior lessons
Concept deep-dive
Layouts
_Layout.cshtml defines site chrome. Nested layouts: area-specific layout sets Layout = "~/Views/Shared/_CorporateLayout.cshtml".
Partial views
Stateless HTML snippets: @await Html.PartialAsync("_MainNav") or Tag Helper <partial name="_MainNav" />. Prefer PartialAsync — supports async I/O.
View components
Classes inheriting ViewComponent with Invoke/InvokeAsync. Use when you need DI, database queries, or encapsulation — e.g. cart item count from session + DB.
public class CartSummaryViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync()
{
var count = await _cartService.GetItemCountAsync(User);
return View(count);
}
}
Invoke in Razor: @await Component.InvokeAsync("CartSummary")
Hands-on — ShopNest Corporate Website
- Create corporate layout with header/footer sections.
- Extract
_SiteHeader.cshtmlpartial with nav links. - Build
NotificationBellViewComponentshowing unread count. - Add
@section Stylesfor page-specific CSS.
Common errors & best practices
- Partial view with heavy DB logic — move to view component or service.
- Sync Partial in async view — use PartialAsync to avoid thread pool starvation.
- View component name must end with ViewComponent (convention).
Interview questions
Q: Partial vs View Component?
A: Partials are dumb templates; view components have classes, DI, and async data loading.
Q: What is @RenderSection?
A: Optional/required placeholder in layout filled by child views.
Summary
- Layouts provide consistent ShopNest corporate chrome
- Partials for static fragments; view components for stateful widgets
- Always prefer async rendering in modern ASP.NET Core
Previous: Views and Razor Syntax
Next: Models and ViewModels
FAQ
Can view components be invoked from controllers?
Yes — return ViewComponent("CartSummary") from an action for AJAX fragments.
Nested layouts — how many levels?
As needed; each view sets its Layout property explicitly.