August 28th 2020
By Toni Torlakovic, .NET Developer at Klika
So, what are View Components?
View Components are an awesome feature of ASP.NET Core, that allows us to take advantage of the power of Razor View Pages and language features of C#, and combine them into nice components that can be used anywhere you have reusable rendering logic that's too complex for a partial view.
Creating a View Component
A view component class can be created by any of the following:
• Deriving from ViewComponent
• Decorating a class with the [ViewComponent] attribute, or deriving from a class with the [ViewComponent] attribute
• Creating a class where the name ends with the suffix ViewComponent
View Components must be public, non-nested, and non-abstract classes. The view component name is the class name with the "ViewComponent" suffix removed. It can also be explicitly specified using the ViewComponentAttribute.Name property.
Today we will be making a simple register and display users app. After scaffolding our app, using ASP.NET Core Web Application template, we will create a really simple View Component for displaying a table and name it “UserTable” + ViewComponent suffix.
As we can see in the picture above, we have derived from the ViewComponent class and added the ViewComponent suffix to our name. Every view component has to implement Invoke or InvokeAsync method.
We have created a UserService as well, which we use to separate our data access code. We are using EFCore InMemory database provider to store our testing data. We can also see one of the benefits of View Components which is dependency injection. We have injected our UserService class and use it to get all of our registered users.
View Components also consist of some markup code (Default.cshtml) which we keep in our view components folder, which you can see in the picture below.
Invoking View Components
View Components are invoked by calling the InvokeAsync method of Component helper class.
We can also invoke View Components as tag helpers, but first, we have to register the assembly containing the view component using the @addTagHelper directive. They can also be invoked directly from a controller action.
As we can see above, View Components nicely separate and encapsulate server-side logic necessary to render output. Just like Controllers, View Components are easily testable, as they can be written to have no side effects, which means fewer bugs.
For further reading...
I suggest you consult the following link View components in ASP.NET Core
Subscribe to our newsletter for the latest
news and job openings at Klika.