Ok, so I’m trying to be a good ASP.NET citizen and write out my control output through the verbosity that is the HtmlTextWriter interface. All is well, but I keep running into the issue of not being able to quite figure out how to write out a <br /> tag using the proper writer code.

 

My first guess would be:

 

writer.RenderBeginTag(HtmlTextWriterTag.Br);

writer.RenderEndTag();

 

but that’s not getting the expected results:

<br>

</br>

 

The right way to do this is:

 

writer.WriteBeginTag("br");

writer.Write(HtmlTextWriter.SelfClosingTagEnd);

 

which properly generates:

 

<br />

 

But this got me thinking – isn’t this basically just like hardcoding the value as:

 

writer.Write("<br />");

 

In both cases I’m actually forcing the full <br /> tag to be explicitly written regardless of the type of output generated.

 

I’m just thinking out loud here. The reason for using the HtmlTextWriter interface over just building a string supposedly is that you can apply different rendering adapters to the output. Basically a different HtmlTextWriter can be passed and that writer potentially can interpret the more generic HtmlTextWriter syntax into adaptable Html/XHtml and potentially WAP or whatever.

 

But writing code like the above basically defeats this. Question is, what’s the right way to write this so it would be adaptive?

 

Further upon checking a little closer my pages are set up to use XHTML as the page layout schema. Yet when I checked the HtmlTextWriter type passed to my control in this case, it’s being passed as an HtmlTextWriter rather than the expected XHtmlTextWriter…

 

I haven’t looked at the details in 2.0, but how does ASP.NET decide when to use the XHtmlTextWriter? It seems it would have to look at the page in combination to the user agent in order to determine the writer to use... 

 

I was searching around regarding a few of these topics and I ran into a few interesting posts (here’s one) that try to tell you that all non-HtmlTextWriter output is evil. In many cases the point made is that adaptive rendering is not available to plain written output.

 

Duh – if you create ASPX pages that have static markup text that you yourself create on the page, no amount of adaptive rendering will help you. If you have a couple of Response.Write() statements or you use a StringBuilder to output text to a literal control, that’s hardly going to change those same dynamics…

 

While I certainly would recommend using an HtmlTextWriter when possible let’s not forget that writing the HTW code is a heck of a bit more involved that spitting out a string. It depends entirely on the scenario involved. Certainly if you build a resusable control it’s a good idea to use a HTW, but on page code that is tied to a very specific HTML schema anyway the value of using a HTW is much less obvious…