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>
    [HtmlAttributeName("asp-button")]
    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();
                output.Attributes.Remove(output.Attributes["class"]);
            }
 
            //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.

[HtmlAttributeName(“asp-button”)]
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:

taghelper3.png

Advertisements

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 = "http://quotesondesign.com/wp-json/posts?filter[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
        output.Content.SetHtmlContent(html);
    }
}

Step 2: Add the Tag Helper to a view

<random-quote></random-quote>

 


Here’s how it looks when run:

taghelper2.png

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?

<email-support></email-support>

or

taghelper1.png

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","mailto:Support@IanVink.com"));
        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="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" >
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" 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>.

<email-support></email-support>

 


The result:

taghelperemail.png

Beautiful button, beautiful markup