autocomplete 技术,已经不稀罕了,各大搜索引擎普遍使用好多年了
那在extaspnet里面如何实现呢
翻阅了一下extjs的一些实现方法,麻烦,还要写json来生成字符串做为数据源
咱目的是用最少的代码实现效果,好了,开始做
首先看数据库,用的SQL2000,里面有一个表 FILM,里面有12000笔记录
代码前台(VS+extaspnet V2.3.5 test.aspx)
[xhtml]view plaincopyprint?
<htmlxmlns="/1999/xhtml">
<headrunat="server">
<title>无标题页</title>
</head>
<body>
<formid="form1"runat="server">
<ext:PageManagerID="PageManager1"runat="server"/>
<ext:PanelID="Panel1"runat="server"Width="500px">
<Items>
<ext:DropDownListID="DropDownList1"runat="server"Width="300px"></ext:DropDownList>
</Items>
</ext:Panel>
</form>
</body>
</html>
代码后台(C# test.aspx.cs 添加了一些注释):
[c-sharp]view plaincopyprint?
usingSystem;
usingSystem.Collections;
usingSystem.Configuration;
usingSystem.Data;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.HtmlControls;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Xml.Linq;
usingSystem.IO;
usingSystem.Data.Sql;
usingSystem.Data.SqlClient;
namespacetestrd
{
publicpartialclasstest:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
if(!IsPostBack)
{
//页面首次加载时,对下拉框修改,这里改变了下拉框长度,并且添加了一个监听事件keyup,在敲下字符后,触发下拉框查询事件
ExtAspNet.PageContext.RegisterStartupScript
(
"vard=Ext.getCmp(""+DropDownList1.ClientID+"");"+
"d.listWidth=500;"+
"d.addListener(/"keyup/",function(f,e){"+
"vararr=["8","16","17","37","38","39","40"];"+
"varx=e.keyCode;"+
"for(varn=0;n<arr.length;n++){if(parseInt(arr[n])==parseInt(x)){return;}}"+
"__doPostBack("loaddata",document.getElementById(/""+DropDownList1.ClientID+"/").value);"+
"});"
);
}
else
{
//这里就是keyup触发的事件了,代码是把输入的关键字在数据库里查询,注意在SQL里面,如果数据量大,不要用like来模糊匹配,会慢,用charindex效率要好些
if(Request["__EVENTTARGET"]=="loaddata")
{
SqlConnectionConn=newSqlConnection(ConfigurationManager.ConnectionStrings["etConnectionString"].ToString());
SqlCommandcmd=newSqlCommand(string.Format("SELECT*FROMFILMwherecharindex("{0}",id)>0orcharindex("{0}",name)>0",Request["__EVENTARGUMENT"]),Conn);
Conn.Open();
SqlDataReaderdr=cmd.ExecuteReader();
DropDownList1.Items.Clear();
while(dr.Read())
{
DropDownList1.Items.Add(newExtAspNet.ListItem(dr["id"].ToString()+"-"+dr["name"].ToString(),dr["id"].ToString()));
}
dr.Close();
//下面这句话是有道理的,extjs默认效果在autocomplete之后,值为变成下拉框的第一项,有点破坏效果,这里纠正过来,可以输入多个关键字
ExtAspNet.PageContext.RegisterStartupScript("document.getElementById(/""+DropDownList1.ClientID+"/").value=""+Request["__EVENTARGUMENT"]+"";");
}
}
}
protectedoverridevoidRender(HtmlTextWriterwriter)
{
StringWriterstrWriter=newStringWriter();
base.Render(newHtmlTextWriter(strWriter));
writer.Write(
strWriter.ToString()
.Replace("id:/""+DropDownList1.ClientID+"/",","id:/""+DropDownList1.ClientID+"/",editable:true,hideTrigger:true,")
);//偷天换日效果,替换extjs字符串,加入2个属性,这2个属性在后期改的话我测试会出错,可能写法不对,就直接写在这里,分别是让下拉框可以编辑,并且隐藏右边的下拉按钮
}
}
}
代码不复杂吧
来看看效果如何