TagHelper子标签未转义属性值

时间:2017-01-14 11:37:19

标签: javascript encoding asp.net-core-mvc tag-helpers tagbuilder

无论我如何尝试对其进行换肤,我都无法从我的TagHelper获取Google Analytics onclick属性的输出,以免被转义。特别是单引号。

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);

输出onclick="ga'send', 'event', 'Navbar', 'Links', 'Guides');"

我需要的是gaOnClick="ga('send', 'event', 'Navbar', 'Links', 'Guides');"

嵌套标签元素是否可行,或者我是否需要以不同的方式处理它?<​​/ p>

1 个答案:

答案 0 :(得分:0)

早上大部分时间都在努力寻找解决方案,但在发布后不久,我偶然发现了一个解决方案!

基于Creating html helpers without encoding,但基于Convert IHtmlContent/TagBuilder to string in C#添加了实用程序类,解决了问题。

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

listItemTag.InnerHtml.AppendHtml(decodedLinkTag);