首页 > 解决方案 > TagHelperOutput 将属性添加到结束,而不是开始

问题描述

我注意到 TagHelperOutput Attribute.Add,将文本添加到每个属性的开头。如何让它为每个属性添加到末尾。

base.Process(context, output);
output.Attributes.Add("class","test");

所以目前如果现有类是“按钮”,新类将是“测试按钮”。我希望它是 html 树中所有类的“按钮测试”

这个问题是针对 TagBuilder 的,

TagBuilder AddCssClass 顺序,添加到开头,末尾如何添加新类?

标签: c#html.netasp.net-core.net-core

解决方案


您可以CreateOrMergeAttribute在标签助手中自定义一个方法,并首先将新的 css 类添加到属性列表中。如下所示:

    public class EmailTagHelper: TagHelper
{
    private const string EmailDomain = "contoso.com";

    // Can be passed via <email mail-to="..." />. 
    // PascalCase gets translated into kebab-case.
    public string MailTo { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "a";    // Replaces <email> with <a> tag

        var address = MailTo + "@" + EmailDomain;

        output.Attributes.SetAttribute("href", "mailto:" + address);
        output.Content.SetContent(address);

        CreateOrMergeAttribute("class", "test", output);
    }

    private void CreateOrMergeAttribute(string name, object content, TagHelperOutput output)
    {
        var currentAttribute = output.Attributes.FirstOrDefault(attribute => attribute.Name == name);
        if (currentAttribute == null)
        {
            var attribute = new TagHelperAttribute(name, content);
            output.Attributes.Add(attribute);
        }
        else
        {
            var newAttribute = new TagHelperAttribute(
                name,
                $"{currentAttribute.Value.ToString()} {content.ToString()}",
                currentAttribute.ValueStyle);
            output.Attributes.Remove(currentAttribute);
            output.Attributes.Add(newAttribute);
        }
    }
}

结果截图:

在此处输入图像描述


推荐阅读