View Components in ASP.NET Core
Implementing View Components in ASP.NET Core application
We have all been familiar with Partial views: A view that can be reused across the web application and is rendered as a child view. Partial views can be returned from the controller just as regular views using ViewResult. Partial view is normally rendered in the main views using @Html.Partial()
method.
View Components got introduced in ASP.NET Core which is way more powerful than the Partial views. View Components have their own class for writing the logic and do not depend upon controllers for their implementation. They can also utilize the power of dependency injection. For example, you want to implement Social icons in your application but they come dynamically with different colors and URLs associated with them. View Components can be used here.
Implementation:
Let us implement a View Component: RestaurantCountViewComponent.cs which will help us in getting the total count of restaurants from the database.
Your Project -> Add RestaurantCountViewComponent.cs
Note: Don't forget to use ViewComponent in the name of your class so that the framework can know it's a view component and it can be handled accordingly.
public class RestaurantCountViewComponent : ViewComponent{private IRestaurantData restaurantData { get; }public RestaurantCountViewComponent(IRestaurantData _restaurantData){this.restaurantData = _restaurantData;}public Task<IViewComponentResult> InvokeAsync(){var count = restaurantData.GetData("").Count();return Task.FromResult<IViewComponentResult>(View(count));}}
If we give a closer look at the above code, we can see View Component is a C# class derived from the base class of ViewComponent. It also supports constructor injection and we did for IRestaurantData which implements our database operations as we will be needing GetData() method to bring the list of restaurants from the database.
If we see the InvokeAsync method there we can load our data and it returns the data wrapped within a View which is basically to render a partial view with the name of ‘Default’.
Folder structure to create that Default.cshtml partial view should be as below:
In our Shared folder we maintain a structure -> Components -> RestaurantCount -> Default.cshtml
Inside Default.CSS HTML I have written some code to render the count of restaurants:
@model intThere are @Model Restaurants<a asp-page="./List" class="btn btn-default" style="color: blue;">View All</a>
Post that we can call the ViewComponents from anywhere inside a view -> I have added in the footer of _Layout.cshtml so the count can be visible throughout the application:
<vc:restaurant-count></vc:restaurant-count>
How it looks like:
If you liked reading this article, give it a clap. You can reach me in the comments section if you have any questions or suggestions.