在百度和谷歌,autoComplete对我们来说再普通不过了,下面我们就通过Ajax Control Toolkit来实现
AutoComplete功能。
Ajax Control Toolkit:
关于如果把Ajax Control Toolkit引入到我们的VS,下面是社区链接:
首页:https://ajaxcontroltoolkit.codeplex.com/
http://www.asp.net/ajaxlibrary/act.ashx
AutoComplete示例
AutoComplete.aspx
<%@ Page Language="C#" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
测试AutoComplete<%--<input type="text" id="search" />--%>
<asp:TextBox ID="search" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteSearch" TargetControlID="search" MinimumPrefixLength="1" ServicePath="~/AutoCompleteService.asmx" ServiceMethod="GetSearchTerms" runat="server">
</asp:AutoCompleteExtender>
</div>
</form>
</body>
</html>
AutoCompleteService.asmx
<%@ WebService Language="C#" Class="AutoCompleteService" %>
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data.SqlClient;
using System.Collections.Generic;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
[System.Web.Script.Services.ScriptService]
public class AutoCompleteService : System.Web.Services.WebService {
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
[WebMethod]
public string[] GetSearchTerms(string prefixText, int count)
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SimpleListsConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand(
"SELECT DISTINCT TOP(@nrows) Name FROM Lists WHERE Name like @term", con);
cmd.Parameters.AddWithValue("nrows", count);
cmd.Parameters.AddWithValue("term", prefixText + "%");
List<string> suggestions = new List<string>();
con.Open();
using (SqlDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection))
{
while(dr.Read())
{
suggestions.Add(dr[0].ToString());
}
return suggestions.ToArray();
}
}
}
最终的效果如图所示:
更多示例:http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/Default.aspx
欢迎大家提出宝贵意见!