How to generate valid XHTML with .NET
A common problem is that the Web Forms and Web Controls in ASP.NET generate invalid XHTML. Amongst these errors are invalid attributes and inline elements without a correct block element container, as well as good ol’ HTML comments in a script block, which prevents you from sending your XHTML with the application/xhtml+XML MIME type.
All these errors are automatically created when the page in question is being rendered in the web browser, meaning that even if you write flawless code you will still fail to get it valid.
To the rescue, some solutions to take care of this:
- A C# class to make your ASP.NET pages XHTML valid
- Valid XHTML within .NET
- Producing XHTML-Compliant Pages With Response Filters
Another option can be to write your own fix and customize it after your specific needs. This should take something from a day and up, depending on where you set the bar.
Or maybe you’re one of the people that hope ASP.NET 2.0 will take care of all this? In that case, I recommend you reading Charl van Niekerk’s posts ASP.NET 2.0 - Part 1 and particularly ASP.NET 2.0 - Part 2.
ASP.NET 2.0 outputs lovely (*irony*) things like:
<form onsubmit="javascript:return WebForm _ OnSubmit();">
and
document.all ?
document.all["Login1_UserNameRequired"] :
document.getElementById("Login1_UserNameRequired")
(for the vast IE 4 support required?) and still HTML comments in scripts block.
And when it comes to semantics, structure and unobtrusive JavaScript, it’s a mess.
Don’t get me wrong, I think it’s great that it validates, but only validating doesn’t necessarily make it good code. Validation is just one of the components necessary for a good web page; there’s, for instance, also semantics, accessibility and unobtrusive JavaScript (or, as important, offering a way for it working without JavaScript as well; kind of connects back to accessibility).
My advice to you: some way or another, make the extra effort to make sure your XHTML from .NET is valid. It’s not that big of a deal, and it’s totally reusable in your next .NET-based project.
Do you have experience of above techniques to make it valid, or some other way to accomplish it? Please feel free to share!


