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
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>
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With