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 ...