Getting Around ASP.Net's Single Form Model

4/14/2008

I'm certain that you've run into this issue multiple times, let's say you have a login form on the right hand side of a web page and on the header for your site you have a site search functionality and maybe a form in the middle of the page. Now when you enter data into the login form and press enter, it does a postback but thinks that you clicked on the site search button... Basically when you press enter inside a form it will click the first button it finds within the form, an annoying feature of the single form model that ASP.Net uses. However there are multiple ways around it.

Use Multiple Forms

We can actually use multiple forms within a page. All we need to do is create a form and not use the runat="server" tag. The page will treat each of the forms separately. Yay! Now we can have as many forms as we want! But what about the drawbacks from this approach?  You can't use objects such as the Textbox or Label outside of the form with the runat="server" tag. So the other forms will be normal HTML forms. This means that you'll have to deal with the button presses, etc. yourself. Not to mention, depending on the layout of your page and the objects that you're using, you won't be able to use this method anyway as you can't embed one form within another successfully. So let's look at another method.

Override the Form Class

This seems to be a somewhat popular approach, although I've yet to figure out why exactly. But basically you can create your own form object, render it yourself, etc. by using the HTMLContainerControl... To be honest, this might have been a good idea back in .Net 1.0 but since the advent of 2.0 this approach is just too much work. And let me show you why I say that with the last approach (and probably the best of the three).

Use the DefaultButton Tag

Since .Net 2.0, panels have a tag named DefaultButton. Putting a button's ID in this tag will allow the person to press enter within the panel and have it call the correct button by default. So you can still have the one form and all you have to do is for any set of input boxes, buttons, etc. that you want to treat as a form, put a panel around it, set the DefaultButton tag, and you're set. You can use all the Labels and Text boxes you want and it doesn't require any extra code.

Anyway, I hope this helps you out. Try it out on your site, leave feedback, and as always happy coding.



Comments