Search code examples
c#asp.net-core

Add style element to html in a TagHelper


I was trying to write tag helper. I reached a result like below. I would like to read your negative comments, if any.

In an ASP.NET Core View I have the following:

<div style-height="100px">test</div>

And I the a Tag Helper with the following TagHelper:

[HtmlTargetElement("div", Attributes = StylePrefix + "*")]
public class SetStyleTagHelper : TagHelper
{
    private const string StylePrefix = "style-";
    [HtmlAttributeName("style")]
    public string CssStyle { get; set; }

    private IDictionary<string, string> _styleValues;

    [HtmlAttributeName("", DictionaryAttributePrefix = StylePrefix)]
    public IDictionary<string, string> StyleValues
    {
        get
        {
            return _styleValues ?? (_styleValues =
                new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase));
        }
        set { _styleValues = value; }
    }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        var item = _styleValues.First().Key;
        var value = _styleValues.First().Value;
        if (!string.IsNullOrEmpty(CssStyle))
        {
            item.Insert(0, CssStyle);
        }

        if (item.Any())
        {
            output.Attributes.Add("style", item + ":" + value);
        }
    }
}

Solution

  • In your process method you can try this:

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
         var MystyleBuilder = new StringBuilder();
         foreach (var style in _styleValues)
         {
             MystyleBuilder.Append($"{style.Key}:{style.Value}; ");
         }
    
         if (!string.IsNullOrEmpty(CssStyle))
         {
             MystyleBuilder.Insert(0, CssStyle + "; ");
         }
    
         if (MystyleBuilder.Length > 0)
         {
             output.Attributes.Add("style", MystyleBuilder.ToString());
         }
    }
    

    When I use multiple styles:

    <div  style-color="red" style-font-size="36px">
        Test code
    </div>
    

    I can see multiple styles are accepted: enter image description here