August 28, 2023

Custom Tag Helpers in ASP.NET Core

Tag Helper allows you to add or modify HTML elements from server-side code. In Razor markup, the Tag Helper looks like standard HTML elements. It provides more productive syntax than manually writing the C# Razor markup.

Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files.

(Microsoft Docs - Tag Helpers in ASP.NET Core)

To create a custom Tag Helper, you need to inherit from built-in TagHelper class. For example we have this Tag Helper,

public class StringTagHelper : TagHelper
{
   public override void Process(TagHelperContext context, TagHelperOutput output)
   {
      output.TagName = "span";
      output.TagMode = TagMode.StartTagAndEndTag;

      output.Attributes.Add("data-entity", "customer");

      base.Process(context, output);
   }
}

This Tag Helper will output the span element and add a custom attribute data-entity with value customer.

In the Razor markup, we can use this Tag Helper as:

<string field="CustomerID"></string>

Ofcourse we can add any extra/custom attributes to html tags, these will not interrupt with Tag Helpers.

The browser will render the final output as:

<span field="CustomerID" data-entity="customer"></span>

To use the Tag Helpers in the views, you need to set its scope, usually we define the scope in Views/_ViewImports.cshtml file.

Tag Helpers scope is controlled by a combination of @addTagHelper, @removeTagHelper, and the "!" opt-out character.

To make the required TagHelper avialable for one or more views we use @addTagHelper.

If you create a new ASP.NET Core web app named MyApplicationTagHelpers, the following Views/_ViewImports.cshtml file will be added to your project:

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

Some points for above code:

  • The code above uses the wildcard syntax ("*") to specify that all Tag Helpers in the specified assembly (Microsoft.AspNetCore.Mvc.TagHelpers) will be available to every view file in the Views directory or subdirectory.
  • The first parameter after @addTagHelper specifies the Tag Helpers to load ("*" is used to load all Tag Helpers)
  • The second parameter "Microsoft.AspNetCore.Mvc.TagHelpers" specifies the source assembly from which we want to load the Tag Helpers. It can be current project's assemly or any reference to external library.

References:

Related Post(s):

No comments:

Post a Comment