View Components
View components are a new feature introduced in ASP.NET Core. They are similar to partial views; however, they are more powerful in nature.
When you use partial views, you have a dependency on the controller. However, when you use the ViewComponent
attribute, you do not have to depend on the controller. So, we are able to establish a separation of concerns and have better testability. Even though the existing partial view HTML Helper is still supported, it is preferable to use the view component whenever you want to show a reusable piece of information when you are using .NET Core.
Creating a View Component
You can create a view component using any of the following methods:
- Create a class by deriving one from the
ViewComponent
attribute - Enhance a class with the [
ViewComponent
] attribute or derive it from the class that has the [ViewComponent
] attribute - Use the convention by creating a class that ends with a suffix
ViewComponent
attribute
Whichever option you choose, the view component...