ViewComponents

In this lesson, we will learn how to factor out entire presentation logic fragments composed of a graphic and a logical part.

Sometimes there is a duplicated controllers’ code that is used to feed the same duplicated Razor markup fragments.

ASP.NET Core MVC allows developers to factor out all these controller-code / Razor-markup duplicate pairs in entities called ViewComponents. Like the controller/view pairs, ViewComponents also contain a logical part coded as a standard C# class and a graphic part coded with a Razor view.

ViewComponents may accept parameters passed to the logical part of the ViewComponent that processes them with the help of services coming from the dependency injection engine to fill ViewModels that are passed to views.

As an example of ViewComponent usage, think of a list of products shown in several action methods of several controllers but with all products filtered and sorted in various ways. We may factor out the whole logic for getting the list of products and for displaying them in a ViewComponent that receives both the filtering and sorting conditions as input parameters.

This way, the various controllers only have to pass filtering and sorting conditions to their views. Their views will then display the list of products with the given filtering and sorting conditions by calling the reusable ViewComponent and passing it the filtering and sorting conditions.

The logical part of ViewComponents

The logical part of a ViewComponent is a class that inherits from the ViewComponent class. It has an InvokeAsync method that accepts the component’s input parameter as its arguments, as shown in the example below:

Get hands-on with 1200+ tech skills courses.