What is View Components ?
ViewComponents are similar to partial view,that helps you to write reusable components.
Definition According to documentation:
“New to ASP.NET Core MVC, view components are similar to partial views, but they are much more powerful. View components don’t use model binding, and only depend on the data you provide when calling into it.”
View Components :
ViewComponents consists of two parts
1.Class derived from ViewComponent.
2.Result returned from ViewComponent typically a view.
Creating a View-Component :
Let’s create a simple view component. They can be created in any of ways listed below,
1.Derived from View Component class.
2.Decorate with ViewComponent Annotation.
3.class suffixed with ViewComponent.
A sample View Component would look like below:
public class SimpleViewComponent : ViewComponent
public IViewComponentResult Invoke()
Creating a View for ViewComponent :
The runtime searches for the view in the following paths:
Let’s create a sample view named Default.cshtml which says “Hello Simple View Component” in the shared folder for the viewcomponent.
Invoking ViewComponent in the view :
ViewComponent can be be called from view using @Components synchronously/asynchronusly with viewcompanent name.
You can download the sample code from github below