Question

What is the best way to add multiple classes to a tag using HtmlTextWriter?

What I would like to do is something like...

 writer.AddAttribute(HtmlTextWriterAttribute.Class, "Class1");
 writer.AddAttribute(HtmlTextWriterAttribute.Class, "Class2");
 writer.RenderBeginTag(HtmlTextWriterTag.Table);

Resulting in...

<table class="Class1 Class2">

I appreciate I could do...

writer.AddAttribute(HtmlTextWriterAttribute.Class, "Class1 Class2");

However it isn't always this straightforward when building the control dynamically. Are there alternative ways to "append" classes to the tag?

Was it helpful?

Solution

why not extend the writer class and add a AddClass and RemoveClass methods on it which while rendering uses all added class names. Internally you could use a List _classNames to hold then and later just join them

writer.AddAttribute(HtmlTextWriterAttribute.Class,string.Join(_classNames.ToArray(), " ");

Hope that helps!

OTHER TIPS

Just following the previous post idea....

public class NavHtmlTextWritter : HtmlTextWriter
{
    private Dictionary<HtmlTextWriterAttribute, List<string>> attrValues = new Dictionary<HtmlTextWriterAttribute, List<string>>();
    private HtmlTextWriterAttribute[] multiValueAttrs = new[] { HtmlTextWriterAttribute.Class };

    public NavHtmlTextWritter (TextWriter writer) : base(writer) { } 

    public override void AddAttribute(HtmlTextWriterAttribute key, string value)
    {
        if (multiValueAttrs.Contains(key))
        {
            if (!this.attrValues.ContainsKey(key))
                this.attrValues.Add(key, new List<string>());

            this.attrValues[key].Add(value);
        }
        else
        {
            base.AddAttribute(key, value);
        }
    }

    public override void RenderBeginTag(HtmlTextWriterTag tagKey)
    {
        this.addMultiValuesAttrs();
        base.RenderBeginTag(tagKey);
    }

    public override void RenderBeginTag(string tagName)
    {
        this.addMultiValuesAttrs();
        base.RenderBeginTag(tagName);
    }

    private void addMultiValuesAttrs()
    {
        foreach (var key in this.attrValues.Keys)
            this.AddAttribute(key.ToString(), string.Join(" ", this.attrValues[key].ToArray()));

        this.attrValues = new Dictionary<HtmlTextWriterAttribute, List<string>>();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top