View Components in ASP.NET Core

Implementing View Components in ASP.NET Core application

Rahul Kapoor
Analytics Vidhya
3 min readFeb 3, 2022

--

Photo by Max Duzij on Unsplash

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.

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

Folder structure of a Default view which View Component renders
The folder structure of a Default view which View Component renders

Inside Default.CSS HTML I have written some code to render the count of restaurants:

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:

How it looks like:

Application home page which render View Component in the footer
Application home page which renders View Component in the footer

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.

--

--