如何通过 TagHelper 获取 HTML 属性的值?

How do I get HTML attribute's value by TagHelper?

我有一个简单的 ASP.NET Core 2.1 标签助手,如果 style 属性尚不存在,它会添加它:

[HtmlTargetElement(Attributes = "yellow")] //contains "yellow" attribute
    public class YellowTagHelper : TagHelper
    {
       public override void Process(TagHelperContext context, TagHelperOutput output)
       {
            if (!output.Attributes.ContainsName("style"))
            {
                output.Attributes.SetAttribute("style", "color: yellow;");
            }
            else
            {
                //how to add 'color: yellow;' value, if 'style' attribute exists already?
                //or how to retrieve existing 'style' value? then I will be able to create new one
            }
       }
   }

并按如下方式使用它:

<div class="element1" id="el1id" runat="server" yellow>
        TEST el1 //here is fine
    </div>
    <div class="element2" id="el2id" runat="server" style="background-color: pink" yellow>
        TEST el2 //here I want to add 'color: yellow;'
    </div>

我一直在寻找如何使用我的标签助手更新样式属性值的解决方案。

创建服务

public class ColorService
{

    public ColorService()
    {
    }

    public string GetColor()
    {
        // Add your logic here
        return "Yellow";
    }
}

在你看来,只要注入它

@inject ColorService ColorService;

稍后在视图中:

<div class="element2" id="el2id" runat="server" style="background-color: @ColorService.GetColor()" yellow>
    TEST el2 //here I want to add 'color: yellow;'
</div>

如果您需要将 Db 上下文添加到您的服务中,您可以参考此答案以获取更多详细信息

好的,我找到了我要找的东西。基于 答案的解决方案,包括已经从数据库中获取颜色:

[HtmlTargetElement(Attributes = "yellow")] //contains "yellow" attribute
    public class YellowTagHelper : TagHelper
    {
        private ApplicationDbContext _context;

        public YellowTagHelper(ApplicationDbContext ctx)
        {
            _context = ctx;
        }
       public override void Process(TagHelperContext context, TagHelperOutput output)
       {
            var colors = _context.ColorPanels.FirstOrDefault(); //context
            var colorStyle = "color:" + colors.Element3BackgroundColor; //new color
            if (!output.Attributes.ContainsName("style"))
            {
                output.Attributes.SetAttribute("style", colorStyle);
            }
            else
            {
                var currentAttribute = output.Attributes.FirstOrDefault(attribute => attribute.Name == "style"); //get value of 'style'
                string newAttributeValue = $"{currentAttribute.Value.ToString() + "; " + colorStyle}"; //combine style values
                output.Attributes.Remove(currentAttribute); //remove old attribute
                output.Attributes.SetAttribute("style", newAttributeValue); //add merged attribute values
            }
        }
   }