asp.net ajax 使用AutoCompleteExtender开发自动完成功能(转载)

我以前发表过一篇《通用的自动完成功能 -Ajax + asp.net》,读者反映也比较多,很多朋友都问我要源码,但是由于整理硬盘一不小心把源码删除了,现在我也没有了。

       不过以前使用的方法是采用js异步请求,再通过处理服务器返回的XML流,那样的好处是可以应用于任何开发语言,只要对相应的页面做一些修改即可,但是调 试起来并不太方便,有时候运行起来没看到错误提示,却得不到正确的结果。不过如果你要使用asp.net 2.0以上的版本来开发这个功能的话,可以使用Ajax Control Toolkit中的AutoCompleteExtender控件,非常简单就可以实现。

       首先先概括一下该功能必须的几个要点:
       1、先确认你的开发环境是否支持ajax;
       2、建立实例数据库。
       3、建立一个Webservices,用于自动完成调用使用。

       新建一个项目(我使用的是VS2008,不过VS2005基本上也是同样的使用,如果还不清楚VS2005的Ajax环境配置的请参考相关资料),在新建 的页面中加入一个TextBox和一个AutoCompleteExtender控件,当然要确保页面中form后面紧跟着一个 ScriptManager控件,这是每个asp.net Ajax页面必须的。页面内容如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Kevin.Web.Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<!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>Ajax AutoComplete</title>
    <style type="text/css">
    .autocomplete_completionListElement
{
visibility : hidden;
margin : 0px!important;
background-color : inherit;
color : windowtext;
border : buttonshadow;
border-width : 1px;
border-style : solid;
cursor : 'default';
overflow : auto;
height : 200px;
    text-align : left;
    list-style-type : none;
}

/* AutoComplete highlighted item */

.autocomplete_highlightedListItem
{
background-color: #ffff99;
color: black;
padding: 1px;
}

/* AutoComplete item */

.autocomplete_listItem
{
background-color : window;
color : windowtext;
padding : 1px;
}
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
    </div>
    <asp:TextBox ID="TextBox1" runat="server" Width="250px" autocomplete="off"></asp:TextBox>
    <ajaxToolkit:AutoCompleteExtender
                runat="server"
                BehaviorID="AutoCompleteEx"          <!-- 显示在TextBox下的下拉列表的ID -->
                ID="autoComplete1"
                TargetControlID="TextBox1"               <!-- 该控件作用的控件ID -->
                ServicePath="AutoComplete.asmx"     <!-- 调用的Webservices地址 -->
                ServiceMethod="GetCompletionList" <!-- 调用的Webservices中的方法 -->
                MinimumPrefixLength="1"                   <!-- 最小匹配前缀字符数 -->
                EnableCaching="true"                         <!-- 是否启用缓存 -->
                CompletionSetCount="20"                  <!-- 返回最大的匹配结果数 -->
                CompletionListCssClass="autocomplete_completionListElement"
                CompletionListItemCssClass="autocomplete_listItem"
                CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
                DelimiterCharacters=";, :">                  <!-- 不需要匹配的字符集-->
                <Animations>
                    <OnShow>
                        <Sequence>
                            <%-- Make the completion list transparent and then show it --%>
                            <OpacityAction Opacity="0" />
                            <HideAction Visible="true" />
                           
                            <%--Cache the original size of the completion list the first time
                                the animation is played and then set it to zero --%>
                            <ScriptAction Script="
                                // Cache the size and setup the initial size
                                var behavior = $find('AutoCompleteEx');
                                if (!behavior._height) {
                                    var target = behavior.get_completionList();
                                    behavior._height = target.offsetHeight - 2;
                                    target.style.height = '0px';
                                }" />
                           
                            <%-- Expand from 0px to the appropriate size while fading in --%>
                            <Parallel Duration=".4">
                                <FadeIn />
                                <Length PropertyKey="height" StartValue="0" EndValueScript="$find('AutoCompleteEx')._height" />
                            </Parallel>
                        </Sequence>
                    </OnShow>
                    <OnHide>
                        <%-- Collapse down to 0px and fade out --%>
                        <Parallel Duration=".4">
                            <FadeOut />
                            <Length PropertyKey="height" StartValueScript="$find('AutoCompleteEx')._height" EndValue="0" />
                        </Parallel>
                    </OnHide>
                </Animations>
            </ajaxToolkit:AutoCompleteExtender>
    </form>
</body>
</html>
再建立一个Webservices,其代码如下:
using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;

/// <summary>
///AutoComplete 的摘要说明
/// </summary>
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 (很多新手像我一样开始都没多大留意这句话)
[System.Web.Script.Services.ScriptService]
public class AutoComplete : System.Web.Services.WebService {

    public AutoComplete () {

        //如果使用设计的组件,请取消注释以下行
        //InitializeComponent();
    }

    [WebMethod]
    public string[] GetCompletionList(string prefixText)
    {
        SqlConnection _sqlConnection = new SqlConnection();
        _sqlConnection.ConnectionString = ConfigurationManager.AppSettings["Conn"];
        _sqlConnection.Open();
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = new SqlCommand("SELECT Words FROM [AutoComplete] where Words like '" + prefixText + "%'", _sqlConnection);
        DataSet ds = new DataSet();
        da.Fill(ds);

        List<string> items = new List<string>();
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            items.Add(dr["Words"].ToString());
        }
        return items.ToArray();
    }   
}

最后就是建立一个示例数据库了。
CREATE TABLE AutoComplete(
     [id] int IDENTITY(1,1) NOT NULL,
     [words] nvarchar(50)
) ON [PRIMARY]

往数据库中插入一些测试数据,你就可以开始测试这个应用程序了。

原文地址:https://www.cnblogs.com/blsong/p/1631866.html