19 September 2006

Fixing TreeView control rendering

While I'm on the subject, I thought I would go over another more annoying bug with the .NET framework which affects the TreeView control and (X)HTML compatibility.

The jist of the problem is that when using the TreeView control with client-side script it has a tendancy to render a <script> tag without the required "type" attribute, very annoying seeing as Microsoft likes to sing the praises of the new standards-compliant control rendering in .NET 2.0.

As a fix you can use the same Render method override trick as before, adding in a simple Replace for these non-compliant script tags:

protected override void Render(HtmlTextWriter writer)
{
string renderedHtml = String.Empty;

using (System.IO.StringWriter sw = new StringWriter())
{
HtmlTextWriter newWriter = new HtmlTextWriter(sw);

// Render "MyBase.Render()" to a String instead of the writer

base.Render(newWriter);
newWriter.Flush();
renderedHtml = sw.ToString();

newWriter.Close();

}

// Fix broken (incompatible) <script></script> blocks, such as the one emitted by the TreeView control
renderedHtml = renderedHtml.Replace("<script>", "<script type="\">");

// Write the modified HTML String to the Response's writer
writer.Write(renderedHtml);
}

This also has the added bonus of fixing any other broken script blocks in the currently rendered page
, which is nice..

No comments: