When developing in ASP.Net, much of what we used to do in HTML and classic asp is now wrapped up in the server controls. One of the things that our qa team finds often is incorrect form submission when pressing the enter key.
There are several appropriate ways to handle the enter key.
One thing you can do is define a "default action". For example, if there are several navigation buttons on your page plus a data entry form, it would make sense that any enter key pressed should fire the form submit action.
Another thing you could do is cancel the enter key entirely. If you intend to support more han standard browsers, this is not the best approach. Some users do not actually use a mouse at all. Keep this in mind if you use the following example.
When I have time, I'll show how to implement the first approach using this same script as a starting point.
For now, we're just going to capture the enter key globally for the form. In ASP.Net, the form is the usually the entire page. (Hint: once you've captured the enter key press, you have control of the action. Use control.ClientId to cause a clientside event that will execute the post-back.)
<script language=javascript>
<!--
var bIsEnterKey = false;
function checkKeyPress(){
return !bIsEnterKey;
}
function setKeyPress(){
bIsEnterKey = (event.keyCode.toString() == '13');
window.setTimeout("bIsEnterKey=false;",1000);
//-->
</script>
<form id="Form1" method="post" runat="server" onsubmit="return checkKeyPress();" onkeypress="setKeyPress()">
When the page renders to the client, anything that ASP.net normally adds to the onsubmit event will precede the custome function call. Therefore, the last thing to happen is going to be the enter key check. If you have validators on the page, they will be executed first. If the validation fails, the enter key check will not be called. In most cases, this is desired, but you need to be aware of it. Validators can mess with your head! The good new is that once validation is successful, the enter key function will be called. If the enter key was the source of the form submission, what ever you've defined in the function (in this case: cancel the form submit) is going to happen.
In the rendered page notice the form onsubmit action. This show the result of placing a RequiredFieldValidator on the page. Nothing special needs to happen beyond the code shown above.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
</HEAD>
<body>
<form name="Form1" method="post" action="AdSenseEdit.aspx" language="javascript" onsubmit="ValidatorOnSubmit();return checkKeyPress();" id="Form1" onkeypress="setKeyPress()">
<input type="hidden" name="__VIEWSTATE" value="..." />
<script language="javascript" src="/aspnet_client/system_web/1_0_3705_288/WebUIValidation.js"></script>
<div id="pnlPropFields" align="Center" style="width:600px;">