Tuesday, December 1, 2009

Don't use .RenderBeginTag("pre")

Even in our modern XHTML/DHTML/AJAX world we still sometimes need to use a good old fashioned <pre>
tag. In our Records Management application, Wisdom, we needed to use one to display the contents of a plain text email that had been stored in Wisdom.  So I used the following code fragment:

writer.RenderBeginTag("pre");
writer.Write(HttpUtility.HtmlEncode(textContent));
writer.RenderEndTag();


but this didn't work very well! The first line of the email was indented as shown below:

         This is a
multi line
plain text email.

The reason is that RenderBeginTag uses some (normally helpful) logic internally to indent HTML tags and content so that it is more readable when you view the source. BUT you don't want this inside a <pre> tag because it preserves the whitespace! So you need to use WriteFullBeginTag and WriteEndTag methods on HtmlTextWriter instead:

writer.WriteFullBeginTag("pre");
writer.Write(HttpUtility.HtmlEncode(textContent));
writer.WriteEndTag("pre");

No comments:

Post a Comment