ASP.NET LinkButton - when disabled renders not a valid xHTML.

четвъртък, 26 юли 2007 г.

What is the problem with LinkButton control in ASP.NET?
When you disable a LinkButton i.e. set Enabled="false", ASP.NET renders disabled="disabled" which is not a valid xHTML property.

How we can fix this?
If you view the source code of the LinkButton control and more specific the AddAttributesToRender method, you will notice that it adds the disabled attribute when Enabled is set to false. The second thing you will see there is that no matter you have set or not the PostBackUrl property to string.Empty, the method renders href property and link postbacks i.e. every time when the LinkButton is Enabled.

So what functionality does we have to achieve? When the LinkButton is disabled, we get these five things:

0. Get rid of the disabled="disabled" property.
1. The link must not be clickable (=> there will be no postback).
2. The cursor is not a hand, but as the thing under is simple text (=> the user will not expect that it is clickable ).
3. We have no underlining.
4. The color is grey as a disabled link. Here I'll add, that if you want to make it more flexible for design, you can set a css class name in which designers can add the appropriate color.

Therefore the thing which will have to do are respectively:
0. Set control's Enabled property to true.
1. Set the PostBackUrl to javascript:void(0).
2. Set the cursor to be of type text.
3. Set the text-decoration to none.
4. Set the color to grey.

As in my previous post which you can find here, we will achieve this with the help of control adapters. Here is a sample source code:

This solution shows again the power of control adapters - properly rendered controls of some type in the whole web site just with a few lines of code.

Vesko Kolev's Blog : IDeveloper -