Tuesday, May 02, 2006

ASP.NET HTML Rendering

One of the major marketing statements regarding ASP.NET was its capability to display content differently depending on browser. What actually happends, though, is that Internet Explorer is considered a HTML 4.0 compatible browser, while others are not. If you ever looked at a normal page with a few textboxes and a button on Firefox or Netscape, then you know what I mean.

Example:rendering for FireFox:

<table width="30%" border="2">
<td align="Right">
<span >
Hi there...

rendering for IE:

<table width="30%" border="2">
<td style="FONT-SIZE: large; COLOR: red" align="right">
Hi there...

In this case, if you want to , let's say, replace the innerHTML property of the td, then you lose the color red.Other such changes put the width/height parameters inside the style property or outside it.

Apparently, the difference in rendering comes from the HtmlTextWriter class. For "not compatible browsers" an overridden class is used for rendering: Html32TextWriter.

How to fix it.
The recomended fix for this is change the tag in machine.config. That would make your server compatible to each browser as you see fit. The downside of this, of course, is that your ASP.NET application will render differently for each hosting server making it undeployable.

My fix.
Just inherit the Page class and add this:
protected override void Render(HtmlTextWriter writer)
writer=new HtmlTextWriter(writer.InnerWriter);
base.Render (writer); // or your own rendering logic
and use this page class for all forms.

This will make all controls on the page render for HTML4.0 compatible browsers. In my personal opinion, we will never make sites that are designed to be seen with Internet Explorer 3.2 or Nescape 4 so this will work. Of course, that doesn't make the pages look the same on all browsers. One needs to check out all the details regarding browser compatibilty such as the way the Visual Studio IDE adds or removes DOM incompatible attributes, but it's a major step forwards.