转自:http://tech.ddvip.com/2009-03/1237358650111667.html
当我们输入的时候,下面出现搜索提示,下面我们来说一下实现的过程;
必备条件,如果你没有安装ASP.NET AJAX,请到http://www.asp.net/ajax/下载
第一步:建立一个web服务:在所在项目上右键--添加--新建项--添加一个Web 服务 :AutoCompleteService.asmx,代码如下
/**//// <summary>
/// AutoCompleteService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
[System.Web.Script.Services.ScriptService]
public class AutoCompleteService : System.Web.Services.WebService
{
[WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string[] GetSearchTerms(string prefixText, int count)
{
SqlConnection cn = DataAccess.DC.SqlConn();//连接数据库
SqlCommand cmd = new SqlCommand("SELECT TOP " + count + " KeyName FROM LB_KeyWord WHERE KeyName like '" + prefixText + "%' ORDER BY PageRank DESC", cn);
List<string> suggestions = new List<string>();
cn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
suggestions.Add(dr[0].ToString());
}
dr.Close();
cn.Close();
return suggestions.ToArray();
}
}
第二步:拖控件ToolkitScriptManager :在前台拖入一个ToolkitScriptManager,不推荐用ScriptManager,因为不精简。一定要设置ScriptMode="Release",并且把web.config的debug设置为false,否则文件会很大,让你死的很难看!
<cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" ScriptMode="Release">
</cc1:ToolkitScriptManager>
第三步:拖入一个UpdatePanel控件;
第四步:然后在UpdatePanel内再拖入一个AutoCompleteExtender控件,设置如下:ServicePath="~/AutoCompleteService.asmx" 这个就是设置ServicePath为刚才你建立的那个AutoCompleteService.asmx的路径;TargetControlID="txtKeyWord" 关联的文本框的id,CompletionInterval="300",CompletionInterval:从服务器读取数据的时间间隔,默认为1000毫秒。也就是说,要等1秒钟才显示出来,这个速度太慢了,用户等不起!还是调整为300比较合适。一定要调整!
如果觉得默认的样式不好看可以调整他们的css样式:给出一个参考
.autocomplete_completionListElement
{
visibility: hidden;
margin: 0px !important;
background-color: inherit;
color: #0066b2;
border: buttonshadow;
border-width: 1px;
border-style: solid;
cursor: hand;
overflow: hidden;
height: 235px;
text-align: left;
list-style-type: none;
}
/* AutoComplete highlighted item */
.autocomplete_highlightedListItem
{
background-color: #6caad9;
color: #FFF;
padding: 1px;
}
/* AutoComplete item */
.autocomplete_listItem
{
background-color: window;
color: #aa7239;
padding: 1px;
}
设置的AutoCompleteExtender:
CompletionListCssClass="autocomplete_completionListElement"
CompletionListItemCssClass="autocomplete_listItem"
CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"