View Component Custom Tag Helper in ASP.NET Core MVC

We can add new HTML elements to our existing ones or make our own custom HTML elements with ASP.NET Core MVC's Tag Helper.

Mar 21, 2022 - 12:33
Mar 21, 2022 - 12:33
 0  119
View Component Custom Tag Helper in ASP.NET Core MVC
Tag Helper, Mvc, ASP.NET Core, Programming, thetechfoyer, thetechfoyer.com

This Article helps to understand the concept of View Component Tag Helper in ASP.NET Core MVC

The class that implements the ITagHelper interface is everything that makes up the Custom Tag Helper in AS.NET Core MVC. On the other hand, we may use the TagHelper class to implement this interface thanks to.NET Core MVC. Lets Create a Custom Tag Helper for the View Component - 



Step 1: Create View Component Server-Side File

using Microsoft.AspNetCore.Mvc;
using PracticeMVC.Repository;

namespace PracticeMVC.ViewComponents
{  
    [ViewComponent(Name = "TopArticle")]
    public class TopArticleComponent : ViewComponent
    {
        private readonly IArticleRepository _articleService;

        public TopArticleComponent(IArticleRepository articleService)
        {
            _articleService = articleService;
        }

        public async Task<IViewComponentResult> InvokeAsync(int count)
        {
            return View(await _articleService.GetTopArticlesAsync(count));
        }
    }
}



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

@model IEnumerable<Article>
  <div class="row">
      <div>
          <h4>Articlesh4>
          <table class="table">
              <tr>
                  <th>
                      ArticleId
                  th>
                  <th>
                      Name
                  th>
              tr>
              @foreach (var article in Model)
              {
                  <tr>
                      <td>
                          @article?.articleId
                      td>
                      <td>
                          @article?.Name
                      td>  
                  tr>
              }
          table>
      div>
  div>



Step 3: Register Custom Tag Helper & Custom Tag Helper in _ViewImports.cshtml

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, WebApplication3
@addTagHelper *, WebApplication3.TagHelpers



Step 4: Create a Custom Tag Helper for the View Component

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

namespace WebApplication3.TagHelpers
{
    [HtmlTargetElement("top-article")]
    public class TopArticlesTagHelper : TagHelper
    {
        //IViewComponentHelper: Supports the rendering of view components in a view.
        private readonly IViewComponentHelper _viewComponentHelper;
        public TopArticlesTagHelper(IViewComponentHelper viewComponentHelper)
        {
            _viewComponentHelper = viewComponentHelper;
        }

        //To hold the parameter value required for MyComponentViewComponent
        public int? Count { get; set; }

        [HtmlAttributeNotBound]  // Should not be bound to HTML attributes
        [ViewContext]  // should set with the current ViewContext, on creating the tag helper        
        public ViewContext ViewContext { get; set; }  //Context for view execution.

        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("TopArticle", new { count = Count }).Result;
            output.Content.SetHtmlContent(content);
        }
    }
}



Step 5: Use the Custom Tag Helper in a Razor View

<top-article count=2>top-article>

<vc:top-article count=2>vc:top-article>  

What's Your Reaction?

like

dislike

love

funny

angry

sad

wow

Deepak Talwar Technical Architect and Full Stack Developer with 18+ years of Professional Experience in Microsoft Technologies & PHP Platform. Hands on experience with C#, VB, ASP.NET, ASP.NET MVC, ASP.NET Core, ASP.NET Web API, Linq, ADO.NET, Entity Framework, Entity Framework Core, Sql Server, MYSQL, NoSql, Javascript, Angular, jQuery, AWS, Azure, React, Angular, Laravel, Codeingiter, Serenity, VBA, Cloud Computing, Microservices, Design Patterns, Software Architecture, Web Design and Development.