How to add attributes correctly upon rendering with a HtmlTextWriter?

citronas picture citronas · Oct 18, 2010 · Viewed 13.8k times · Source

I want to add the href attribute to a link element. This is my code:

System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
using (System.IO.StringWriter stringWriter = new System.IO.StringWriter(stringBuilder))
{
 using (System.Web.UI.HtmlTextWriter htmlTextWriter = new System.Web.UI.HtmlTextWriter(stringWriter))
 {

  htmlTextWriter.RenderBeginTag(HtmlTextWriterTag.Ul);
  htmlTextWriter.RenderBeginTag(HtmlTextWriterTag.Li);
  htmlTextWriter.RenderBeginTag(HtmlTextWriterTag.A);
  htmlTextWriter.AddAttribute(HtmlTextWriterAttribute.Href, "http://www.google.de");
  htmlTextWriter.Write("Google");
  htmlTextWriter.RenderEndTag();
  htmlTextWriter.RenderEndTag();


  htmlTextWriter.RenderEndTag();
 }
}

It renders as:

<ul>
 <li><a>Google</a></li>
</ul>

This is what I expected.

<ul>
 <li><a href="http://www.google.de">Google</a></li>
</ul>

What went wrong and how can I fix this issue?

Please don't answer that I could assemble the string in some other way. I want to know how I can achieve this with the HtmlTextWriter

Answer

Gabriel McAdams picture Gabriel McAdams · Oct 18, 2010

When using the HtmlTextWriter, you have to add the attributes BEFORE you add the tag name. Like this:

  htmlTextWriter.RenderBeginTag(HtmlTextWriterTag.Ul);
  htmlTextWriter.RenderBeginTag(HtmlTextWriterTag.Li);

  htmlTextWriter.AddAttribute(HtmlTextWriterAttribute.Href, "http://www.google.de");
  htmlTextWriter.RenderBeginTag(HtmlTextWriterTag.A);
  htmlTextWriter.Write("Google");
  htmlTextWriter.RenderEndTag(); //A

  htmlTextWriter.RenderEndTag(); //LI
  htmlTextWriter.RenderEndTag(); //UL

It will render like this:

<ul>
    <li><a href="http://www.google.de">Google</a></li>
</ul>