DefaultButton - Deal with users hitting ENTER on your forms

Developers tend to assume that users will be always clicking on the buttons to submit forms. Is it a valid assumption? Unfortunately not always ... the simplest example can be quick search, a common component on many sites.

What if user simply hit ENTER instead of clicking on the button next to the text box? Because our button wasn't clicked then of course even handler for Click event won't be invoked. The problem is that users expect that hitting Enter will correctly submit the form. So what can we do?

HtmlForm and Panel classes have a property called DefaultButton. Thanks to this property we can address the issue. First lets check the HtmlForm.DefaultButton property, here is how it can be used:

 

   1:  protected void Page_Load(object sender, EventArgs e) 2:  {

   3:      Page.Form.DefaultButton = btnSearch.UniqueID;

  }

 

That's all what is needed to make sure that post back generated by pressing the ENTER key will be "associated" with the button btnSearch. That is an improvement, but there is another problem to solve, check contact us page:

This is slightly more complex situation as here we would like to have Send button to be the default button for HtmlForm. So what about quick search? The following piece of code will solve it:

   1:  <asp:panel id="pnlSearch" runat="server" defaultbutton="btnSearchButton">

   2:      <asp:textbox id="txbSearchQuery" runat="server" validationgroup="search" maxlength="50" />

   3:      <asp:Button id="btnSearchButton" runat="server" text="Search" validationgroup="search" />

   4:  </asp:panel>

 

By surrounding the quick search controls with ASP.NET panel we can define for that group default button, different default button then the one on HtmlForm. In this simple way it's possible to define arbitrary number of small areas on the page with custom default button.

Another thing worth noticing is that defining unique validation group for all functionally related groups of controls is considered as a good practice. This way you can be sure that submitting one group won't trigger validation somewhere else.

I know that those are not a life-changing features but still I find them very useful, it's good to dust off basics like this from time to time.

posted on 2012-11-30 14:21  ilawrence  阅读(284)  评论(0编辑  收藏  举报