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
public class Options: ViewComponent
{
}
C#
  • Decorate the class using [ViewComponent] attribute
[ViewComponent(Name = "Options")]
public class Options : ViewComponent
{
    public IViewComponentResult Invoke()
    {
       return View();
    }
}
C#
  • Name the class ViewComponent as subfix
public class OptionsViewComponent : ViewComponent
{
   public IViewComponentResult Invoke()
   {
     return View();
   }
}
C#

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 a Task<IViewComponentResult> or IViewComponentResult for a synchronous Invoke or InvokeAsync
  • 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

services.AddRazorPages().AddRazorOptions(opts =>
           {
               opts.ViewLocationFormats.Add("/{0}.cshtml");
           });
C#

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

View Components

Comments

Popular posts from this blog

Use SCSS with ASP.NET Core 5.x or 3.X

Building a Login Flow with .NET MAUI

PySpark Schema Generator - A simple tool to generate PySpark schema from JSON data