Thursday, March 13, 2008

Can we have more than one Default Button per page?

It's been a while since I found out some cool and handy tips in ASP.NET 2.0.

So, what's it this time?
My login page has two buttons which takes the user through two different processes: the login process and registration process. Of course, there're textboxes for username-password and an invitation code that the user needs to enter to go through the registration process.

Now, you've probably guessed the scenario. If you type in the user name and password and hit the return key, the login button's event should fire up. However, if you type an invitation code and hit the return key, the register button's event should fire up.

Traditionally, a form has one default button, which usually is the login button in a login page. We specify the default button property in the form tag. This we know already. In this scenario however, we're going to look at two default buttons with an implemetaion-level being VERY EASY!

All we need to do is put the controls that are required to perform a single process inside a ASP panel and specify the default button inside the panel's html tag (which looks something like the sample below):

asp:panel id="pnlLogin" runat="server" defaultbutton="btnLogin"

Behind the scenes (nothing much here but sheer curiosity):
Well, being a developer, and a curious one at coding (just like the rest of my species), I did a VIEW SOURCE on my page to see how the content is rendered.

The Panel as we all know is rendered as a DIV. However, ASP.NET adds some extra attributes to the DIV like:

onkeypress="javascript:return WebForm_FireDefaultButton(event,'btnLogin')

"As a good practice, I usually put all the controls with the same validation-group inside one panel if I wish to use a default button for the page. Also, now I know that I can have more than one default button in a page."

Well, that's it until next time!

1 comment:

Anonymous said...

Very helpul, thanks a lot !