Skip to main content

How to avoid unexpected postback after pressing Enter in textbox

You fill a form with many input fields. After filling first textbox you mechanically press Enter and see that the page are submitted to the server. Inasmuch as the rest of the fields stay blank the result of this submit is either saving incomplete data or a few validators of type "Field XXX is required." are shown. The well-known situation, is not it? It is not very good to allow such behaviour in a web application, especially because it easily can be corrected.

Of course, there are situations when this is useful (e.g.: you have a single search box and after typing a search keyword it is very convenient to start search by pressing Enter). But in the most cases such behaviour just
annoys visitors.

Surprisingly, but this inconvenience caused by built-in browser conveniences. :)

Convenience #1. If a form contains only textbox then regardless of the submit button presence pressing Enter will send the form to the server.

Candidate solutions
  • If design allows add one more textbox
  • If design allows set the textbox TextMode to "MultiLine". In this case the textbox is rendered as textarea element instead of input type="text"
  • Add an invisible text field (do not confuse with hidden field). See the below example:
<form ... >
<asp:TextBox ... >
<input type="text" style="display:none">

Convenience #2.
If the form contains input type="submit" or input type="image" pressing Enter submits the form using the focused input, if any, or first input on the form.

Candidate solutions
  • In order to rid of input type="submit" do not use a Button with UseSubmitBehavior="True"
  • In order to rid of input type="image" do not use ImageButton. It can be replaced with the following construction:
<asp:LinkButton ID="btn" runat="server">
<asp:Image id="im" runat=server ImageUrl="..." style="border:0px"/>

Appendix. Interrelation between ASP.Net controls and HTML elements.

ASP.Net ControlHTML Element
TextBox (TextMode="SingleLine")input type="text"
TextBox (TextMode="Password")input type="password"
TextBox (TextMode="Multiline")textarea
Button (UseSubmitBehavior="False")input type="button"
Button (UseSubmitBehavior="True")input type="submit"
ImageButtoninput type="image"