Using the System.Web.UI.HtmlTextWriter to create self-closing tags

  • Thread starter Thread starter Nathan Sokalski
  • Start date Start date
N

Nathan Sokalski

I am using the System.Web.UI.HtmlTextWriter, and would like to create tags
that are self-closing (such as <tagname />). The RenderBeginTag method does
not offer the option of making a self-closing tag (I think it should have an
optional boolean parameter to specify whether it is self-closing, but it
doesn't). I know how to make self-closing tags using the Write methods, but
this requires calling a write method for every attribute and style, and does
not allow you to use the System.Web.UI.HtmlTextWriterAttribute or
System.Web.UI.HtmlTextWriterStyle enumerations. Is there a built-in way that
I am missing to make self-closing tags? Thanks.
 
Is there a built-in way that I am missing to make self-closing tags?

I just tried the following code in a simple console app:

HtmlTextWriter writer = new HtmlTextWriter(Console.Out);
writer.RenderBeginTag("p");
writer.RenderBeginTag("img");
writer.RenderEndTag();
writer.RenderEndTag();

This yields the following written in my console:
<p><img /></p>

Doing the same with "div" as argument for the second call to
RenderBeginTag() yields a different result, where the div is printed with
an open and empty body. I believe this i by design, as it does not make
any sense to have a self-closing div.

What kind of HTML element are you working with?
 
Back
Top