...

/

Authoring Tag Helpers

Authoring Tag Helpers

In this lesson, we will learn how to code our custom tag helpers.

A tag helper is a class that inherits from the framework Microsoft.AspNetCore.Razor.TagHelpers.TagHelper abstract class:

Press + to interact
using Microsoft.AspNetCore.Razor.TagHelpers;
...
namespace MvcProject.TagHelpers
{
public class ProtocolTagHelper: TagHelper
{
...
}
}

Defining when the tag helper is applied

The first step in tag helper design is to code its hook conditions, that is, to define when the transformation encoded in the tag helper applies. This can be done with one or more HtmlTargetElement attributes applied to the tag helper class definition. Each attribute specifies an alternative condition. This means that it is enough that the condition specified by a single attribute is satisfied for the tag helper transformation to apply.

Each HtmlTargetElement attribute can specify one or more of the following

  • The name of the tag that the tag helper applies to.
[HtmlTargetElement("protocol")]
public class ProtocolTagHelper: TagHelper
  • Some names of attributes that the tag must contain. In this case, the name of the tag is optional-
[HtmlTargetElement(Attributes = "attr1,attr2")]
public class ProtocolTagHelper: TagHelper
  • The name of the parent tag. In this case, the name of the tag is optional.
[HtmlTargetElement(ParentTag= "div")]
public class ProtocolTagHelper: TagHelper

All conditions stated in an HtmlTargetElement attribute must be verified simultaneously for the tag helper to be executed. Alternative conditions can be coded by adding other HtmlTargetElement attributes. For instance, if we want to implement a tag ...

Access this course and 1400+ top-rated courses and projects.