MenuCochesViewComponent
TheMenuCochesViewComponent is a view component that renders a dynamic menu of cars using the RepositoryCoches data source.
Source
ViewComponents/MenuCochesViewComponent.cs
Constructor
MenuCochesViewComponent
Initializes the view component with repository dependency injection.The repository instance for accessing car data
RepositoryCoches is automatically injected by the ASP.NET Core DI container.
Methods
InvokeAsync
Retrieves the list of cars and passes it to the view component view.Task<IViewComponentResult> - Asynchronous result containing the view with car data
Implementation:
Usage
Invoking in a View
You can invoke this view component in any Razor view using theComponent.InvokeAsync method:
Creating the View Component View
Create a view atViews/Shared/Components/MenuCoches/Default.cshtml:
Views/Shared/Components/MenuCoches/Default.cshtml
Complete Example
Layout with View Component
Views/Shared/_Layout.cshtml
Service Registration
Ensure the repository is registered inProgram.cs:
Program.cs
Benefits of View Components
- Reusable Logic: Encapsulates rendering logic that can be used across multiple views
- Testable: Can be unit tested independently from controllers
- Dependency Injection: Supports constructor injection for data access
- Asynchronous: Supports async data loading with
InvokeAsync - Isolated: Doesn’t use model binding or participate in controller lifecycle
Related
RepositoryCoches
Car repository used by this component
Coche Model
Car model documentation
CochesController
Controller for car operations
Quickstart Guide
See view component usage examples