c# - TagHelperOutput 将属性添加到结束,而不是开始
问题描述
我注意到 TagHelperOutput Attribute.Add,将文本添加到每个属性的开头。如何让它为每个属性添加到末尾。
base.Process(context, output);
output.Attributes.Add("class","test");
所以目前如果现有类是“按钮”,新类将是“测试按钮”。我希望它是 html 树中所有类的“按钮测试”
这个问题是针对 TagBuilder 的,
解决方案
您可以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);
}
}
}
结果截图:
推荐阅读
- c# - 优化霍夫曼表符号检索(顺序和渐进 JPEG)
- postgresql - 如何将 tokio_postgres 与 Warp 一起使用?
- google-apps-script - 如何颠倒拼接的顺序?
- javascript - 在 HTML 中计算引号内的文本的理想方法是什么?
- javascript - 在没有 getElementById 的情况下通过其 ID(作为 var)处理元素是否合适?
- javascript - 在 React 中,在嵌套节点和不同分支中的兄弟节点之间传递数据的首选设计模式是什么?
- memory-leaks - NVIDIA h.264 编码器 MFT 是否泄漏资源?
- swift - 如何返回未指定的测量值
从一个函数? - html - 无法让 CSS translateZ 在 Chrome 上运行
- c++ - 递归函数的执行顺序