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:



ASP.Net Core 2: TagHelper Part 2: Display downloaded Quotes

quote-clipart-9TpbXMnnc.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.

Step 1: Add a new class called RandomQuoteTagHelper to your web project

public class RandomQuoteTagHelper :TagHelper
    public override void Process(TagHelperContext context, TagHelperOutput output)
        //The Html Tag will be a div
        output.TagName = "div";
        var html = "";
        using (var w = new WebClient())
            //Get a random QUOTE
            var url = "[orderby]=rand&filter[posts_per_page]=1";
            //Convert the quote to a dynamic object so we can get the Quote text out
            dynamic quote = JsonConvert.DeserializeObject(w.DownloadString(url));
            html = quote[0].content;
        //Add Html quote to the Div

Step 2: Add the Tag Helper to a view



Here’s how it looks when run:


ASP.NET Core 2: TagHelpers Part 1

images.jpgTagHelpers let you simplify the markup in your Razor pages and improve readability.

Which would you rather have on your Razor Page?




Step 1: Create a new ASP.NET Core project, any template will do. Call it TagThis

Step 2: Add a class called EmailSupport.cs to the web project

This class tells ASP.NET Core how to render the custom tag and is fairly self-explanatory in this basic example

public class EmailSupport :TagHelper
    public override void Process(TagHelperContext context, TagHelperOutput output)
        //The Html Tag will be an Anchor
        output.TagName = "a";
        //Add the link and css class to the anchor tag
        output.Attributes.Add(new TagHelperAttribute("href",""));
        output.Attributes.Add(new TagHelperAttribute("class""btn btn-primary"));
        //Add text to the link
        output.Content.SetHtmlContent("Email Support");

Step 3: Edit the _ViewImports.cshtml file and tell it to add all Tag Helpers from the TagThis assembly. Notice the “*”

@addTagHelper *, TagThis

Step 4: Add Bootstrap and FontAwesome css to your _Layout.cshtml to make it look pretty

<link href="" rel="stylesheet" >
<link href="" rel="stylesheet">

Step 5: Add this markup to a page.

Warning: Your TagHelper class, if its name has CaSe, must be referenced in lowercase with a ‘-‘ separating the words. For example, EmailSupport becomes <email-support>.



The result:


Beautiful button, beautiful markup