Thursday, March 01, 2007

Valid disabled links in ASP.NET

When we published Bunny-Chicken Evil Plots ten days ago I've tried to make it XHTML 1.0 compliant. However I did not succeed at that moment. Control I've created for comic navigation rendered invalid disabled='disabled' attribute for an anchor tag. Not only it is not valid by standards (hence rejected by validator), but has special "dimmed" rendering in IE which cannot be overridden by CSS. At that moment I let it be, thinking it must be me who messed up something, because ASP.NET should be mostly XHTML-compliant.

Last night I decided to make control render valid XHTML and went to look what's wrong. Turns out the source of the problem lies in WebControl and its Enabled property. WebControl is base class for many ASP.NET web controls and should be inherited by custom web controls. One of its main responsibilities is encapsulated in method protected virtual void AddAttributesToRender (HtmlTextWriter writer) which writes "standard" (X)HTML attributes basing on set control properties.

One of that "standard" attributes rendered is 'disabled'. It is rendered if Enabled is set to false (makes sense :)). After some contemplation I've came with the following solution:

protected override void AddAttributesToRender(
    HtmlTextWriter writer)
    bool enabled = Enabled;
    Enabled = true;


    Enabled = enabled;
    // [ some more code here... ]

Idea is to override AddAttributesToRender and before calling method from base class (which you should do if you inherit from WebControl), you enable control. This way disabled attribute won't be set and you are free to customize disabled control as much as you like it. Of course we restore previous value from local variable.

This code is part of AccessibleLinkButton initially created for Web.Comic. Nice thing about the control is that it can post back if JavaScript is enabled, or go to specified URL if JavaScript is disabled or link is middle-clicked (to open in a new tab). Check out how it works at Bunny-Chicken Evil Plots.

1 comment:

Anonymous said...

Great post, I am almost 100% in agreement with you