How to use View Components In ASP.NET Core 5.0 MVC?
View Components In ASP.NET Core 5.0 MVC
The concept of ViewComponet in Asp.Net Core 5 MVC is very similar to a PartialView but it has more potential in it.
ViewComponet renders a small chunk of view which is not a part of the controller or the HTTP life cycle.
Typical usage
- Additonal product suggestions
- Extra navigation menu
- Recently added posts
- A Small notice that has to be rendered in every page
- Sidebar content
How to create a ViewComponent?
- Derive a class from ViewComponent
- Decorate the class using [ViewComponent] attribute
- Name the class ViewComponent as subfix
View search path
The runtime searches for the view in the following paths:
- /Views/{Controller Name}/Components/{View Component Name}/{View Name}
- /Views/Shared/Components/{View Component Name}/{View Name}
- /Pages/Shared/Components/{View Component Name}/{View Name}
The View component class supports dependency injection, it can have parameters.
View Component methods
- Create an
InvokeAsync
method that returns aTask<IViewComponentResult>
orIViewComponentResult for
a synchronousInvoke
orInvokeAsync
- We can pass a model class from the View method which gets passed to the view page
- The parameters comes from where the the method is called there is no involvement of controller or HTTP Life cycle
- The ViewComponent is not accessible as an HTTP end point. It is called from your code or from a View page.
Customize the View Search path
The placeholder in the above code snippet "{0}" represents the path "Components/{View Component Name}/{View Name}".
An Example with parameters
ViewComponent Code
Invoke Component
To Use ViewComponent as a tag helper
To use a view component as a Tag Helper, register the assembly containing the view component using the @addTagHelper
directive. If your view component is in an assembly called
IdentityDemo/(your project name)
, add the following directive to the _ViewImports.cshtml file:
Result
for more details
see the documentation from Microsoft
Comments
Post a Comment