I have a simple ASP.NET Core 2.1 tag helper, that adds style
attribute if does not exist yet:
[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
}
}
}
And using it as follows:
<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>
And I am stuck with finding solution how to update style attribute's value with my tag helper.
Ok, I found what I was looking for. Solution based on >>THIS<< answer, includesalready taking color from 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
}
}
}