On this one particular page the enter key would trigger a postback on an Image Button OnClick event, needlessly bringing up our beautiful UserSearch screen over and over and over again.
Thoroughly stumped, I reached for Google and ended up at Matt Webster’s blog. His thread (sorry I lost the URL) was stocked with more clues than a warehouse full of Agatha Christie paperbacks and, while not providing the answer exactly, it gave me the gist that the Enter Key has a magnetic attraction for the first ‘Submit’ control it can find – in our case the ultra-assertive Image Button that invoked the UserSearch Control with jihadist fervour.
My solution was a trademark brutal hack.
I just put ANOTHER submit button immediately prior to the Image Button and trapped OnClientClick to return false. So my markup ended up looking like this:
asp:LinkButton ID="hackyDefaultButton" OnClientClick="return false; Visible="false"
asp:ImageButton ID="userSearchButton" OnClick="InvokeUserSearch"
So the Enter Key finds the first submit button on the page which is now the hacky default button and does nothing, unless the Page focus is on the ImageButton in which case it fires InvokeUserSearch.
Brutal hacks. Love ’em.
Is the above the worst brutal hack you’ve seen ?
Please feel free to rate/flame my hack, but in the interests of constructive criticism, tell me what I should have done better.
This article by 4GuysFromRolla clearly explains the issue and told me that single-line textboxes will almost always cause a submit to be executed on the first button on the HTML form on the Web Page depending on how your browser implements the HTML 2.0 standard.
In the case of IE, a Web Form with more than one single-line Textbox and a submit button will always generate a postback on the first submit button in the form (unless you have done something explicit to modify that behaviour e.g set a DefaultButton on the form).
They solved the issue in exactly the same way I did !!!
Maybe I’m a genius.