Search code examples
c#asp.netclasshtmltextwriteraddattribute

HtmlTextWriter - Adding multiple classes to a tag


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?


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!