TagHelperOutput 将属性添加到结尾,而不是开始

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

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

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

这个问题是针对 TagBuilder 的,

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


叮当猫咪
浏览 95回答 1
1回答

慕斯王

您可以在标签助手中自定义一个CreateOrMergeAttribute方法,并首先将新的 css 类添加到属性列表中。像下面这样:&nbsp; &nbsp; public class EmailTagHelper: TagHelper{&nbsp; &nbsp; private const string EmailDomain = "contoso.com";&nbsp; &nbsp; // Can be passed via <email mail-to="..." />.&nbsp;&nbsp; &nbsp; // PascalCase gets translated into kebab-case.&nbsp; &nbsp; public string MailTo { get; set; }&nbsp; &nbsp; public override void Process(TagHelperContext context, TagHelperOutput output)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; output.TagName = "a";&nbsp; &nbsp; // Replaces <email> with <a> tag&nbsp; &nbsp; &nbsp; &nbsp; var address = MailTo + "@" + EmailDomain;&nbsp; &nbsp; &nbsp; &nbsp; output.Attributes.SetAttribute("href", "mailto:" + address);&nbsp; &nbsp; &nbsp; &nbsp; output.Content.SetContent(address);&nbsp; &nbsp; &nbsp; &nbsp; CreateOrMergeAttribute("class", "test", output);&nbsp; &nbsp; }&nbsp; &nbsp; private void CreateOrMergeAttribute(string name, object content, TagHelperOutput output)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var currentAttribute = output.Attributes.FirstOrDefault(attribute => attribute.Name == name);&nbsp; &nbsp; &nbsp; &nbsp; if (currentAttribute == null)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var attribute = new TagHelperAttribute(name, content);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; output.Attributes.Add(attribute);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var newAttribute = new TagHelperAttribute(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $"{currentAttribute.Value.ToString()} {content.ToString()}",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; currentAttribute.ValueStyle);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; output.Attributes.Remove(currentAttribute);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; output.Attributes.Add(newAttribute);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}结果截图:
打开App,查看更多内容
随时随地看视频慕课网APP