While view components are primarily invoked from within views, the ViewComponentResult class allows you to directly return a rendered view component from a controller action. This provides a powerful way to integrate view components with your MVC controller logic and leverage their reusable rendering capabilities.
Purpose Dynamic View Component Loading: Use ViewComponentResult to load view components on demand based on the controller’s logic or data. This is particularly useful for rendering complex UI elements that depend on specific data or conditions. Separation of Concerns: Keep your controller actions focused on handling requests and data retrieval, while delegating the rendering of specific UI components to view components. API-like Endpoints: Create API-like endpoints that return HTML fragments (view components) instead of JSON or XML data. This can be helpful for building hybrid applications where you need to combine server-side rendering with client-side JavaScript.
Creating a ViewComponentResult In your controller actions, you can return a ViewComponentResult using the ViewComponent() helper method: return ViewComponent(“ViewComponent Name”, arguments);
ViewComponent Name: The name of the view component you want to invoke. This should match the class name of your view component (without the “ViewComponent” suffix). arguments (Optional): An anonymous object containing the parameters you want to pass to the view component’s InvokeAsync method.
Code // HomeController.cs (Controller) [Route(“friends-list”)] public IActionResult LoadFriendsList() { PersonGridModel personGridModel = new PersonGridModel() { GridTitle = “Friends”, Persons = new List<Person>() { // … (list of friends) … } };
return ViewComponent(“Grid”, new { grid = personGridModel }); }
In this code: Data Preparation: The personGridModel object is created and populated with data for the list of friends. ViewComponentResult: The ViewComponent() method is used to return a ViewComponentResult. It takes two arguments: “Grid”: This indicates that we want to invoke the GridViewComponent. new { grid = personGridModel }