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

时间:2018-12-27 10:11:54

标签: css attributes asp.net-core-mvc asp.net-core-tag-helpers

我有一个简单的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>

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

2 个答案:

答案 0 :(得分:0)

创建服务

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上下文添加到服务中,可以参考此答案以获取更多详细信息 ASP.NET Core 2.1 insert CSS in layout based on data in DB

答案 1 :(得分:0)

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

[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
            }
        }
   }