Challenge:
I have a search box in every asp.net web page with one text box and one submit button. When the visitor clicks the submit button, he will be re-directed to a search result web page since the onClick event is fired on that submit button. But when the visitor finishes his typing and simply hits the enter key, a postback event will be fired on the page level but the onClick event of that submit button could be not fired.
Solutions
After reviewing the HTML codes and HTTP requests, I found out the pair of button name/value has not been sent to the form along with the text box. That was the reason why the page could not decide whether the submit button triggered then not fired the onClick event.
I am using ASP.NET 2.0 and experiencing such issue, and not sure whether ASP.NET 3.5 still have the same issue. But a simple work-around can fix this issue - which is to add one more textbox web control.
For example, if you only have one textbox and submit button, the query string post back to the server will be
default.aspx?txtBOX1=some+value&
But if you have more than one text boxes in your asp.net page, then your string will be
default.aspx?txtBOX1=some+value&txtBOX2=some+value…btnSubmit=Search…
Of course, you do not want the visitors to see your addtional textbox, you should use a style to hide it. Do not use visibility property since that will disable that textbox web control. So your new textbox will look like the below
<asp:TextBox ID=”txtInvisible” runat=”server” Style=”visibility: hidden; display: none;” />
In this way, when the visitor express the Enter key, your first button web control will be fired.
[update: if you have multiple button web controls and want to control which one to be fired while the visitor hits the Enter key, please read on my next post]
Blog Comments