ttmind

Main Navigation

ttmind
  • jim-jams
  • Tech
  • Positive
Login

Login

Facebook Google

OR

Remember me Forgot password?

Don't have account? Signup here.

Sort by Categorys

.Net

PHP

Java

JavaScript

Database

Server

Client Side

Tools

Artificial Intelligence

Cloud

Hybrid Development

Event

Smart City

Education

Security

Scrum

Digital Marketing

APP Development

Business

Internet

Simulation

Art

Network

Microservices

Architecture

Technology

Leadership

    Top Articles

  • How Does Social Media Bring People Together?
    TTMind Author
  • How to read appSettings JSON from Class Library in ASP.NET Core
    Anil Shrestha
  • Printing Support In Asp.Net Core
    TTMind Author
  • HOW TO EXTRACT TEXT FROM IMAGE USING JAVASCRIPT (OCR with Tesseract.js)?
    Prakash Pokhrel
  • Images Upload REST API using ASP.NET Core
    Prakash Pokhrel
  • Related Topic

  • How to read appSettings JSON from Class Library in ASP.NET Core
  • Printing Support In Asp.Net Core
  • Images Upload REST API using ASP.NET Core
  • How to use IActionFilter, IAsyncActionFilter in ASP.NET Core MVC?
  • ASP.NET CORE - Blazor CRUD operation using ADO.NET
  • Tech
  • About Us
  • Contact Us
  • TechHelp
  • PositiveHelp
  • Jim-Jams Help
  • Terms & Conditions

© Copyright ttmind.com

Main Content

How to Create Custom Tag Helper in ASP.NET Core

.Net .Net Core about 7 years ago || 9/20/2018 || 2.1 K View

  • Hide

If you working in ASP.NET Core and you still not using Tag Helper then you missing something, which can help you and your team well. So the question is what Tag Helper?

Tag Helper

"A tag helper is any class that implements the ITagHelper interface"

Tag Helper provide a way to server-side code to participate in creating and rendering HTML elements in Razor files. Tag helper is a new feature and it seems similar to HTML Helper, which help us render HTML. To know more What is Tag helper visit https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro?view=aspnetcore-2.1

So yes there is the difference between Tag Helper and HTML Helper

Tag Helper attached to HTML elements inside our Razor views and can help us to write markup that is cleaner and easier to read. But HTML Helper will be invoked as methods which are mixed with HTML inside our Razor views.

Now have a look, how easily we can create our Custom Tag Helper,
Though the scope of Tag Helper is little big it's good to create a different project which can be used in any project, but for simplicity, we will just create a simple class which just implements ITagHelper interface.

With this simple Tag Helper, we will replace any HTTP URL in our content with HTML anchor tag. If you creating just a simple Blog page or website and you want this feature then it's a really good one. As this Tag Helper is for pattern matching of URL it is using RegularExpressions. A code is shown below,

using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

namespace CustomTagHelpers.TagHelpers
{
    [HtmlTargetElement("p")]
    public class AutoLinkerHttpTagHelper : TagHelper
    {
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            var childContent = await output.GetChildContentAsync();
            // Find Urls in the content and replace them with their anchor tag equivalent.
            output.Content.SetHtmlContent(Regex.Replace(
                 childContent.GetContent(),
                 @"\b(?:https?://)(\S+)\b",
                  "<a target=\"_blank\" href=\"$0\">$0</a>"));  // http link version
        }
    }
}

So basically override void Process Method of TagHelper which have two Parameters

  • TagHelperContext context,
  • TagHelperOutput output

And you can see how easy to work it. It also has one more overload which is not async, so you have an option as per nature of work you can use override option.

I had taken this example from https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/authoring?view=aspnetcore-2.1 as it is simple and easy to learn quickly. This link have many examples so it will help you looking for more examples.

Now we have import our Tag Helper in our View so that our views can understand it, so to import it open our _ViewImports.cshtml file which can be found in our root of Views folder. [If you do not have this then you can just add this file];
And then add

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

The first line is for the inbuilt Tag Helpers and the last one is our Custom one, with this * model it will all the Tag Helpers that we have in that namespace, if we want only few Tag Helpers then we can just use those namespaces.

Now we all set, we have to add some text in view where we want to test this Tag Helper, so just a line your view where we want to see it,

<p>Visit us at http://www.ttmind.com</p>

And run your Application, now we can see our above line will be rendered with,

<p>Visit us at <a target="_blank" href="http://www.ttmind.com">http://www.ttmind.com</a">

So start using it, it is a very powerful helper which leads you to manage your projects with similar and consistent tags across the projects.

  • 1
  • 0
  • 0
    • Facebook
    • Twitter
    • Google +
    • LinkedIn

About author

Alok Pandey

Alok Pandey

Love to share what I know.

Reset Your Password
Enter your email address that you used to register. We'll send you an email with your username and a link to reset your password.

Quick Survey