View Component Tag Helper in ASP.NET Core MVC

View Component Tag Helper in ASP.NET Core MVC

I will discuss View Component Tag Helper in ASP.NET Core MVC Application with Examples in this article. Please read our previous article discussing Custom Tag Helper in AS.NET Core Application.

View Component Tag Helper in ASP.NET Core MVC:

In ASP.NET Core MVC, the Tag Helper feature provides a way to create and use custom tags in Razor views. One of the common uses of tag helpers is to enhance code reusability and readability, especially when working with components like views.

Although View Components are a separate feature in ASP.NET Core, we can integrate them with Tag Helpers to create more readable Razor views. Let’s try to understand the process of creating a View Component and then integrating the View Component with a Custom Tag Helper in an ASP.NET Core MVC Application.

What are the View Components in ASP.NET Core MVC?

As we already discussed, View Component is a new feature introduced in ASP.NET Core that enables displaying data (view + data) on a view file independently from the entire HTTP Life Cycle. Please read the following article, where we discussed View Components in detail.

https://dotnettutorials.net/lesson/view-components-in-asp-net-core-mvc/

As we already discussed in our View Component article, a view component consists of 2 files in ASP.NET Core. They are as follows:

  • Server-Side File (.cs file).
  • Client Side File (.cshtml file)

The Server-Side (.cs) File can be created anywhere in the project. But we generally create a new folder (with the name Components, ViewComponents) at the root level of the project, and we need to place all the view components inside this new folder.

The Client-Side (.cshtml) file of a view component must be placed at a specific location. They are as follows:

Location1: If we want to call the view component from the controller’s action method, then we need to add the view component client-side file at the following location-

/Views/{Controller Name}/Components/{View Component Name}/{View Name}

Location2: If we want to call the view component from the other cshtml file, then we need to add the view component client-side file at the following location-

/Views/Shared/Components/{View Component Name}/{View Name}

Location3: If we are using a view component in Razor pages, then we need to add the view component client-side file at the following location-

/Pages/Shared/Components/{View Component Name}/{View Name}

Note: The name for each view component file should be Default.cshtml.

Create a View Component:

First, create a folder named ViewComponents within the project root directory.

Suppose the name of the view component server-side file is MyComponent; then, we must add a suffix ViewComponent to its name. Hence, the final name of the view component server-side file will be MyComponentViewComponent.

The View Component class must and should be derived from the ViewComponent class. This ViewComponent class provides methods for the logic and data preparation needed to render the view component.

So, create a class file with the name MyComponentViewComponent.cs within the ViewComponents folder and copy and paste the following code into it.

using Microsoft.AspNetCore.Mvc;
namespace TagHelpersDemo.ViewComponents
{
    public class MyComponentViewComponent : ViewComponent
    {
        public IViewComponentResult Invoke(string param)
        {
            // Logic or Data Retrieval
            // Returns the Default view with the passed param
            return View("Default", param);  
        }
    }
}
View Component Client-Side File in ASP.NET Core MVC:

We are using ASP.NET Core MVC and want to invoke the view component from a view file. Hence, we need to place the client-side file at the following location.

Views/Shared/Components/MyComponent

Once you create the Default.cshtml view file within the above-specified folder, your Views folder should look as shown below.

View Component Client-Side File in ASP.NET Core MVC

Now, open Default.cshtml view file and then copy and paste the following code into it.

@model string

<div>
    This is the content of the View Component with parameter: @Model
</div>
Create a Custom Tag Helper for the View Component

The Custom Tag Helper in AS.NET Core MVC is a class that implements the ITagHelper interface. However, .NET Core allows us to implement this interface with the TagHelper class. So, creating a Custom Tag Helper is a three-step process as follows:

  • Add a new class to your project
  • Inherit from TagHelper.
  • Override the Process or ProcessAsync method.

First, create a folder named TagHelpers inside the project root directory. This is the place where we will be creating our custom Tag Helpers. So, create a class file with the name MyComponentTagHelper.cs within the TagHelpers folder and copy and paste the following code into it. The following example code is self-explained, so please go through the comment line for a better understanding.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace TagHelpersDemo.TagHelpers
{
    [HtmlTargetElement("my-component")]
    public class MyComponentTagHelper : TagHelper
    {
        //IViewComponentHelper: Supports the rendering of view components in a view.
        private readonly IViewComponentHelper _viewComponentHelper;

        //Initializing the _viewComponentHelper through Constructor
        public MyComponentTagHelper(IViewComponentHelper viewComponentHelper)
        {
            _viewComponentHelper = viewComponentHelper;
        }

        //This Property will hold the parameter value required for MyComponentViewComponent
        public string? Param { get; set; }

        //Indicates the associated Microsoft.AspNetCore.Razor.TagHelpers.ITagHelper property
        //should not be bound to HTML attributes.
        [HtmlAttributeNotBound]

        //Specifies that a tag helper property should be set with the current ViewContext
        //when creating the tag helper.
        [ViewContext]

        //Context for view execution.
        public ViewContext ViewContext { get; set; }

        //Override the Process Method
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            //IViewContextAware: Contract for contextualizing a property activated by a view with the ViewContext.
            //Contextualize: Contextualizes the instance with the specified viewContext.
            ((IViewContextAware)_viewComponentHelper).Contextualize(ViewContext);

            var content = _viewComponentHelper.InvokeAsync("MyComponent", new { param = Param }).Result;
            output.Content.SetHtmlContent(content);
        }
    }
}
Register the Custom Tag Helper in _ViewImports.cshtml

Here, we need to add the namespace of our tag helper to _ViewImports.cshtml to make it available for all our views. So, modify the _ViewImports.cshtml file as follows, and please replace the namespace as per your application.

@using TagHelpersDemo
@using TagHelpersDemo.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, TagHelpersDemo
@addTagHelper *, TagHelpersDemo.TagHelpers
Use the Custom Tag Helper in a Razor View

Finally, we can use the custom tag helper in a Razor view. So, modify the index.cshtml view of Home Controller as follows:

@{
    ViewBag.Title = "Index";
    Layout = null;
}

<p>Invoking View Component using Custom Tag helper</p>
<my-component param="Hello from Tag Helper!"></my-component>
<br/>
<p>Invoking View Component using Built-in vc Tag helper</p>
<vc:my-component param="Hello"></vc:my-component>

When rendered, this will invoke the Custom Tah helper, which will invoke the View Component, which will render its corresponding view.

By creating this tag helper for the view component, we can use a custom tag to embed the view component in your Razor views, leading to more readable and maintainable code.

I will discuss Cache Tag Helper in ASP.NET Core in the next article. Here, in this article, I try to explain View Component Tag Helper in ASP.NET Core MVC Application with Examples. I hope you enjoy this View Component Tag Helper in ASP.NET Core article.

Leave a Reply

Your email address will not be published. Required fields are marked *