View Component là gì?
View Components là một tính năng mới trong ASP.NET Core MVC, tương tự như partial views nhưng mạnh hơn nhiều. Chúng đặc biệt hữu ích cho những phần giao diện có logic phức tạp, như:- Navigation menus
- Shopping cart sidebar
- Login panel
- Recent posts widget
- Admin dashboards
Lưu ý: View Components hoàn toàn tương thích với Razor Pages và có thể được sử dụng ở bất kỳ đâu bạn cần logic phức tạp kết hợp với rendering.
View Component vs Partial View
| Tiêu chí | Partial View | View Component |
|---|---|---|
| Logic | Embedded hoặc qua ViewBag | Tách riêng trong class |
| Rendering | Synchronous | Synchronous hoặc Asynchronous |
| Model binding | Via weakly-typed ViewData | Strongly-typed parameters |
| Testability | Khó unit test | Dễ unit test |
| Controller required | Không | Không |
| Dependency Injection | Không (trừ @inject) | Đầy đủ DI support |
| Use case | Simple rendering | Complex business logic + rendering |
Tạo View Component
Bước 1: Tạo View Component Class
Tạo class kế thừa từViewComponent:
Bước 2: Tạo Razor View
Tạo view tại đường dẫn:Quy ước đặt tên
Class Name
| Cách đặt | Ví dụ |
|---|---|
Suffix ViewComponent | PriorityListViewComponent |
| Hoặc attribute | @[ViewComponent] PriorityList |
View Name
Theo mặc định, View Component tìm view tênDefault:
Gọi View Component
Từ View
Tag Helper (Khuyến nghị)
Tag Helper (Razor Class Library)
Từ Controller
Từ Razor Page
View Component với Strongly-Typed Data
Định nghĩa Model
View Component Class
Razor View với Strong Type
View Component Synchronous
Nếu không cần async, có thể override phương thứcInvoke:
Các phương thức View Component
View Method
Content Method
Other Methods
| Method | Mô tả |
|---|---|
View(model) | Trả về view với model |
View(viewName, model) | Trả về view cụ thể với model |
Content(content) | Trả về HTML content string |
EmptyResult() | Trả về empty response (204 No Content) |
View Component Context
ViewContext
Truy cậpHttpContext, RouteData, và các thông tin request: