ASP.net 多个按钮回车响应

有两个button,两个textbox,需要输入textbox1后回车就postback到button1的后端事件,textbox2类似。很明显需要在客户端代码实现。

解决方法:

首先了解.Net中控制控件的postback是通过这个js函数控制的:

<script language="javascript" type="text/javascript">
 <!--
 function __doPostBack(eventTarget, eventArgument) {
 var theform;
 if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) {
 theform = document.Form1;
 }
 else {
 theform = document.forms["Form1"];
 }
 theform.__EVENTTARGET.value = eventTarget.split("$").join(":");
 theform.__EVENTARGUMENT.value = eventArgument;
 theform.submit();
 }
 // -->
 </script>

也必须添加两个hidden的文本框到客户端,写到<form>中

<input type="hidden" name="__EVENTTARGET">

<input type="hidden" name="__EVENTARGUMENT">

后端.cs文件中的Page_Load添加:

TextBox1.Attributes.Add("onkeydown","javascript:if (13 == window.event.keyCode){__doPostBack('Button1','');return false;}");
   TextBox2.Attributes.Add("onkeydown","javascript:if (13 == window.event.keyCode){__doPostBack('Button2','');return false;}");

实例:

<script language="VB" runat="server">
Protected Sub Page_Load(Src As object, E As EventArgs)
  If Not IsPostBack Then
    TextBox1.Attributes.Add("onkeydown","javascript:if (13 == window.event.keyCode){__doPostBack('Button1','');return false;}");
    TextBox2.Attributes.Add("onkeydown","javascript:if (13 == window.event.keyCode){__doPostBack('Button2','');return false;}");
  End If
End Sub
</script>

<body>
<form ID="Form1" runat="server">
<script language="javascript" type="text/javascript">
 <!--
 function __doPostBack(eventTarget, eventArgument) {
 var theform;
 if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) {
 theform = document.Form1;
 }
 else {
 theform = document.forms["Form1"];
 }
 theform.__EVENTTARGET.value = eventTarget.split("$").join(":");
 theform.__EVENTARGUMENT.value = eventArgument;
 theform.submit();
 }
 // -->
</script>
<input type="hidden" name="__EVENTTARGET">
<input type="hidden" name="__EVENTARGUMENT">

<asp:TextBox  ID="TextBox1" runat="server" /><asp:Button ID="Button1" runat="server" />
<asp:TextBox  ID="TextBox2" runat="server" /><asp:Button ID="Button2" runat="server" />
</form>

</body>

实现。这实际上是将微软本身提供的体制反着用了一次,不得已而为之,但总算实现了。

参考: http://blog.joycode.com/ceocio/archive/2005/01/05/42429.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值