今天遇到个输入框回车提交查询,开始以为直接有服务器端事件呢,看了下TextBox 服务器端事件,发现没有keydown事件。找了下baidu。直接用的是客户端事件(onkeydown)来提交按钮的
其实,想像也是,原先在asp中,所有的控件都是HTML控件,可以在上边写各个事件(onchanged,onkeypress,onkeydown等),现在asp.net 服务器端事件最后也是生成Html控件的。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>TextBox回车自动查询</title>
<script language="javascript">
function keydown(btn) {
if (window.event.keyCode == 13) {
event.keyCode = 9;
event.returnValue = false;
document.all[btn].click();
}
}
</script>
</head>
<body>
<form id="form1" runat="server" >
<div>
<asp:TextBox ID="txb_seach_input" runat="server" ></asp:TextBox>
<asp:Button ID="btnsearch" runat="server" Text="查询" onclick="btnsearch_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
txb_seach_input.Attributes.Add("onkeydown", "keydown('"+btnsearch.ClientID+"')");
}
protected void btnsearch_Click(object sender, EventArgs e)
{
Label1.Text = "当前输入内容为:" + txb_seach_input.Text ;
}
}
}