TagHelper child tag unescaped attribute value

358 Views Asked by At

No matter how I try to skin it, I can't get the output from my TagHelper for the Google Analytics onclick attribute to not be escaped. Specifically the single quotes.

TagBuilder listTag = new TagBuilder("ul");
listTag.AddCssClass(ListClass);

foreach (Category category in Links)
{
    bool isSelectedCategory = category.PathValue == ViewContext.RouteData.Values["controller"].ToString()
        || (category.PathValue == "home"
            && ViewContext.RouteData.Values["controller"].ToString().ToLowerInvariant() == "home"
            && ViewContext.RouteData.Values["action"].ToString().ToLowerInvariant() == "index");
    TagBuilder listItemTag = new TagBuilder("li");
    listItemTag.AddCssClass(ListItemClass);
    if (isSelectedCategory) { listItemTag.AddCssClass(ListItemActiveClass); }

    TagBuilder linkTag = new TagBuilder("a");
    linkTag.InnerHtml.Append(category.Name);
    linkTag.AddCssClass(LinkClass);
    if (isSelectedCategory) { linkTag.AddCssClass(LinkActiveClass); }
    linkTag.Attributes["href"] = urlHelper.RouteUrl("default", new
    {
        controller = category.PathValue,
        action = "index",
        topicPathString = category.DefaultTopic?.PathValue,
        articlePathString = category.DefaultTopic?.DefaultArticle?.PathValue
    });
    if (EnableGoogleAnalytics)
    {
        string gaOnClick = $"ga('send', 'event', 'Navbar', 'Links', '{category.Name}');";
        linkTag.MergeAttribute("onclick", gaOnClick);

    }
    listItemTag.InnerHtml.AppendHtml(linkTag);
    listTag.InnerHtml.AppendHtml(listItemTag);
}

output.Content.SetHtmlContent(listTag);
base.Process(context, output);

Outputs onclick="ga'send', 'event', 'Navbar', 'Links', 'Guides');".

What I need is gaOnClick="ga('send', 'event', 'Navbar', 'Links', 'Guides');".

Is this possible with nested tag elements, or do I need to approach it in a different way?

1

There are 1 best solutions below

0
On

Having spent most of the morning trying to find a solution, it's only fitting that I stumble across one shortly after posting!

Based on Creating html helpers without encoding, but with an added utility class based on Convert IHtmlContent/TagBuilder to string in C#, has solved the problem.

HtmlString decodedLinkTag = new HtmlString(
    System.Net.WebUtility.HtmlDecode(
        Utility.TagBuilderToString(linkTag)));

listItemTag.InnerHtml.AppendHtml(decodedLinkTag);