青松阳光

关注于.NET技术
posts - 43, comments - 64, trackbacks - 17, articles - 7
  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理

updated on 1/9/2008

有时候我们希望在TextBox输入完之后,直接敲击Enter键要求页面提交,在IE里有时候可以成功但有时候确出乎意料的未提交。
那么IE里敲击Enter键有没有什么规律呢。经查找资料发现还是有的:

1. When the Enter key is pressed within an ASP.NET Web Form that has multiple single-line textboxes, the form will submit and the Button Web control that appears first in the HTML page's markup will have its Click event fired.

2. If you have a Web Form with just one single-line text input (even if there are additional input fields, like CheckBoxLists, RadioButtonLists, DropDownLists, and so on), hitting enter in the text input will not cause the Button Web control's Click event to fire when using Internet Explorer.


因此正好在我看到这个资料的第二天, 有一个项目客户回馈:

In SubContList, the ENTER button should be the same as clicking Find.

在这个页面里,只有一个TextBox,一个查找按钮,正好符合上述的第二条规律,如果在TextBox里输入查询条件,直接敲击Enter键是不行的。因此只好再添加另外一个TextBox,但是要让其隐藏:

<asp:TextBox runat="server" style="DISPLAY:none;VISIBILITY:hidden" ID="Textbox1" Text="In order to accept enter event"/>

这样就符合第一条规则了,可以正常提交页面了。

我的项目是asp.net1.1的,IE6,不知道在asp.net2.0里可以如何处理。
另外大家可以在这里看到相关资料
Enter and the Button Click Event
Using JavaScript to prevent or trigger form submission when ENTER is hit
Two Common Pitfalls When Submitting a Web Form Using the Enter Key

在asp.net2.0中,加入了DefaultButton和DefaultFocus特性,极大的方便了我们的开发,推荐以下blog:
http://weblogs.asp.net/scottgu/archive/2005/08/04/421647.aspx

本篇blog涵盖的有:

Default Buttons in ASP.NET 2.0
Default Focus in ASP.NET 2.0
Focus on Errors
Putting it all together

Feedback

#1楼    回复  引用  查看    

2007-06-08 10:34 by 木野狐      
用 form 的 "DefaultButton" 属性即可。

代码:
<form id="form1" runat="server" defaultbutton="btnTest">
<div>
<asp:TextBox ID="txtTest" runat="server" />
<asp:Button ID="btnTest" Text="Test" runat="server" OnClick="btnTest_Click"
/>
</div>
</form>

#2楼    回复  引用  查看    

2007-06-08 10:37 by Dicky      
似乎没发现未提交的状况.偶是XPsp2 + IE 7. ASP.NET 2.0里在 form 加上 defaultbutton="loginBtn"("loginBtn"为提交按钮的ID),就会在文本框上回车自动执行loginBtn的点击事件.

#3楼    回复  引用    

2007-06-08 10:37 by 姓名 [未注册用户]
你知道为什么吗?

#4楼    回复  引用  查看    

2007-06-08 10:39 by 木野狐      
即使用附加一个隐藏 input 的办法,也不必要加服务器端控件,直接加一个 <input /> 的 html 元素即可。

#5楼    回复  引用  查看    

2007-06-08 11:17 by 风海迷沙      
搞不定就用客户端的js处理,还可以指定相应的点击按钮

#6楼    回复  引用  查看    

2007-06-08 14:00 by <span style="color:red;">Anders Li      
@木野狐
DefaultButton是.NET 2.0新增的属性。而博主用的是.NET 1.1。
在.NET 1.1里的确是存在这样的问题。我的做法是用js判断回车键,然后进行提交。

#7楼    回复  引用  查看    

2007-06-08 22:53 by 孤剑      
好东西,学习了。

现在客户要求使用 1.1 ,所以不得已,就用了 js

标题  
姓名  
主页
Email (只有博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2008-01-09 18:02 编辑过