Tuesday, 12 June 2007

Today I've got a question if it is possible to make ASP.NET not to render the div tag around it's special hidden fields (i.e.: "__EVENTTARGET"). I have never thought about it before, so I didn't know the answer. I had to investigate. After a brief overview of the state of things, I have come to believe that there is no easy way to do achieve this. To confirm my suspicions I used the Reflector.

I have found that it is indeed possible to make ASP.NET not render the div tag if RenderDivAroundHiddenInputs property of HtmlTextWriter class returns false or if LegacyRendering is enabled. You can enable the later by setting xhtmlConformance mode to Legacy in Web.config file. Unfortunately the RenderDivAroundHiddenInputs property of HtmlTextWriter class always returns true and you cannot change it because it is internal. Additional investigation has shown that there is a class that overrides that property to return false. The class was: XhtmlTextWriter.

How to make ASP.NET use XhtmlTextWriter instead of normal HtmlTextWriter? I was unable to find a way to configure ASP.NET to do it. Setting xhtmlConformance mode to strict doesn't help. Google also is not very helpful. The only way seams to be either override Render method of a Page class like this:

protected override void Render(HtmlTextWriter writer)
    base.Render(new XhtmlTextWriter(writer));

Or better yet to override the CreateHtmlTextWriter like this:

protected override HtmlTextWriter CreateHtmlTextWriter(System.IO.TextWriter tw)
    return new XhtmlTextWriter(base.CreateHtmlTextWriter(tw));

This however requires you to use a kind of BasePage class for each page in your project (which is good, but not everyone likes it). Another concern I have is the fact that there is very little information on XhtmlTextWriter class, and the one that is available seams to suggest that the class is meant rather for mobile devices.

There is one more way you can try to solve the problem. You can use Response.Filter to do the job, but I would not recommend it unless you really, REALLY need to get rid of the div. Creating such a filter can really hurt performance. If you decide you REALLY need to, Mads Kristensen has an example of how to make a filter. He is using Response.Filter to move ViewState to the bottom of the page.

kick it on DotNetKicks.com