Tuesday, June 19, 2007

I'm a big ASP.NET lover mostly because of the fact that I can work with HTML in a more abstract way presented to me in form of controls. While authoring controls, it is always my goal to write as little HTML code as possible. To make it possible I relay heavily on composite controls. Sometimes however it is not possible or simply to complex to achieve a result using a composition of controls. That's where the Render method comes in handy.

Using Render method and accompanying HtmlTextWriter object we can write plain HTML using writer.Write() method. This however forces us to write HTML which I try to avoid. Here also the  HtmlTextWriter offers some alternatives that include writer.RenderBeginTag() method and HtmlTextWriterTag enumeration. Using them, we can generate HTML in a way that allows for some degree of compile time checking and some enhancements. If we just used the following code:

writer.RenderBeginTag("h1");

there is little that protects us from misspelling the tag name. There is also no way for a RenderBeginTag method to help us adjust the output to target concrete platform. We are simply telling it to write "h1" element and so it does because we expect it to. Consider however an alternative version:

writer.RenderBeginTag(HtmlTextWriterTag.H1);

This time, instead of passing "h1" string literal, we pass a value of a HtmlTextWriterTag enumeration. Now we are suggesting that we need the H1 element, but we leave a space for interpretation. What the writer object renders is up to it. Keep in mind however that HtmlTextWriter class and moreover the XhtmlTextWriter class are there to allow for customization. If there is a device that requires all tags to be uppercase, than it can be done using a special writer object that knows and targets the concrete device.

One thing that I only recently discovered however is how to write a "<br />" without writing "<br />". If we try to use the mentioned overload like this:

writer.RenderBeginTag(HtmlTextWriterTag.Br);
writer.RenderEndTag();

We will get an invalid HTML:

<br>

</br>

The solution is to use the writer.WriteBreak() method. It will output the required form of "<br />" and shield us from using plain text.

You may ask if it really matters. True, it is a very thin line of abstraction here but I like it this way.

kick it on DotNetKicks.com