Creating CSS Control Adapters
I often experience a gap between the drag-n-drop ASP.NET cowboys of Visual Studio and standards-aware CSS developers. The cowboys produce fast results in a fire-and-forget environment and couldn’t care less for the quality of the HTML output, which in turn drives the standardistas insane.
One solution to this is to use CSS Adapters. In short, this will give the ASP.NET developer a bit more control over the output. Unfortunately, I’ve noted several times in just one month that a lot of people don’t even know of the existence of CSS Adapters.
For instance, the GridView control is arguably the most popular control in the 2.0 Framework, replacing the old classic DataGrid. Having a look at the client side, the control will be rendered into a <table> element and it will always insert a border attribute, regardless how you configure the control’s border properties (sad but true). There is no easy way using the vanilla VS.NET to avoid this presentational attribute from appearing in your markup. I suppose you could write a XSLT response filter to achieve a similar result, but what we need is a very easy way of doing it. Otherwise only very few will even bother.
CSS Adapters to the rescue. They enable custom CSS rendering for the ASP.NET controls. In plain English, this means that you can choose to render the GridView as <table>, <ul>, a bunch of <div> elements or whatever. By controlling your markup, you can control your presentational styles.
Technically speaking, the CSS adapters plug-into the ASP.NET server controls and override the rendering output logic of that control. That means you don’t have to change any code-behind, since the same syntax is used for the control.
How is this done? First, you create a class that derives from the System.Web.UI.Adapters.ControlAdapter (an abstract class that defines the basic functionality for all adapters). Within the new class, you override the appropriate methods to customize the markup. Then the new ControlAdapter class needs to be registered in a .browser file within the /App_Browsers directory.
By changing the .browser file, you can also configure the adapters to be used only with specific versions of specific browsers, or sending different renderings to different browsers.
But be careful doing this. You really should have the same output for all browsers, or else you’re in a time machine back to the nineties. Use refID="Default" to enable your adapters for all browsers.
If you don’t want to do all this, there are sufficiently advanced control classes available in the tutorial templates.
CSS Adapters is not a perfect solution and most people couldn’t care less about the output quality anyway, but at least it’s a possibility to avoid the default markup.