ASP.Net Core 2: TagHelper Part 3: Custom html attributes

tag 3 logo.pngIn Part 1 you learned how to create a simple email TagHelper for ASP.Net Core. We will expand on that project and add a TagHelper which will add values to the html class attribute of any div.

Our goal is to write this in our Razor pages:
<div asp-button=“true”>My Button</div>

and have this Html created:
<div class=“btn btn-primary”>My Button</div>

Step 1: Using the project you wrote in Part 1 or Part 2, add a new class called ButtonTagHelper.cs

/// <summary>
/// Only Divs with the attribute asp-button are affected
/// </summary>
[HtmlTargetElement("div", Attributes = "asp-button")]
public class ButtonTagHelper : TagHelper
    /// <summary>
    /// The asp-button attribute will get auto-mapped to this property
    /// </summary>
    public string Button { getset; }
    public override void Process(TagHelperContext context, TagHelperOutput output)
        //If there was an asp-button attribute add a bootstrap btn class
        if (this.Button == "true")
            //Get the current value of the class attribute
            var currentClassValue = "";
            if (output.Attributes.ContainsName("class"))
                currentClassValue = output.Attributes["class"].Value.ToString();
            //Add a new class attribute with the previous values
            output.Attributes.Add("class""btn btn-primary " + currentClassValue);

Let’s break this down:

[HtmlTargetElement(“div”, Attributes = “asp-button”)]

This tells ASP.NET Core that the following TagHelper is to be applied to an div with an asp-button attribute.

public string Button { get; set; }

A bit of magic here. ASP.NET Core will convert the value of the asp-button attribute and will add it to the property. The property must be public.

Here’s the result:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s