ASP.NET ajaxToolkit AutoCompleteExtender自动补全示例源码

来源:互联网 发布:淘宝的电子发票在哪里 编辑:程序博客网 时间:2024/05/21 10:40

示例源码下载    其他示例下载



aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="autocomplete.aspx.cs" Inherits="SasSystem.autocomplete" %><%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %><%@ Import Namespace="Utility.Web" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    <title>Ajax Autocomplete(ajax自动完成)</title>    <script src="/js/ajax.AutocompleteTable/jquery-1.8.3.min.js"></script>    <style type="text/css">        /*AutoComplete flyout */        .autocomplete_completionListElement {            visibility: hidden;            margin: 0px !important;            background-color: inherit;            color: windowtext;            border: buttonshadow;            border-width: 1px;            border-style: solid;            cursor: pointer;            overflow: auto;            text-align: left;            list-style-type: none;            font-family: Verdana;            font-size: 13px;            padding: 0;        }        /* AutoComplete item */        .autocomplete_listItem {            background-color: white;            padding: 1px;        }        /* AutoComplete highlighted item */        .autocomplete_highlightedListItem {            background-color: #e9f5f7;            padding: 1px;        }    </style>    <script type="text/javascript">        function SetContextKey() {            var autoComplete = $find('<%=autoComplete.BehaviorID %>');            if (autoComplete != null) {                autoComplete.set_contextKey('userName,loginName');//经过算法处理后,筛选条件拼接为:userName like '%a%' or loginName like '%a%'            }         }        function ajaxCompleteCallBack(source, eventArgs) {            $("#AjaxCompleteSelectedValue").text("返回结果: id=" + eventArgs.get_value() + " | text=" + eventArgs.get_text());        }    </script></head><body>    <form id="form1" runat="server"><asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager><asp:TextBox ID="txtSearch" runat="server" onkeydown="SetContextKey();"></asp:TextBox><ajaxToolkit:AutoCompleteExtender ID="autoComplete" runat="server" TargetControlID="txtSearch"    ServicePath="~/AjaxService/webservice.asmx"    ServiceMethod="GetAutoCompleteExtenderData"    MinimumPrefixLength="1"    CompletionInterval="200"    CompletionSetCount="10"    FirstRowSelected="true"    EnableCaching="false"    UseContextKey="true"    OnClientItemSelected="ajaxCompleteCallBack"    CompletionListCssClass="autocomplete_completionListElement"    CompletionListItemCssClass="autocomplete_listItem"    CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"></ajaxToolkit:AutoCompleteExtender><div id="AjaxCompleteSelectedValue"></div>        <pre>CompletionListCssClass="autocomplete_completionListElement" CompletionListItemCssClass="autocomplete_listItem" CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"AutoCompleteExtender的其它属性虽然到现在这个程度它已经可以动起来了, 但是还有很多属性我们没有用到, 下面我们逐个了解它的其它属性.TargetControlID这是必须指定的属性, 它指出Extender 应该寄宿到哪个控件身上, 上面的例子已经演示了它的用法, 就把目标控件的ID 赋给它即可.ServicePath指出要使用的服务的路径, 这里指的是asmx文件的路径, 而不是cs文件, 因为这里两个文件都处于根目录, 所以直接写入了文件名, 如果两个文件不在同一目录, 还要指出该asmx文件所在的路径. 例如: ../xx.asmx .ServiceMethod返回数据的函数, 填入目标函数名即可.MinimumPrefixLength最少需要录入的长度, 因为我们指定了1, 所以只要敲入一个字符, 就会立即弹出下拉列表, 如果把这个值改为3, 则至少要录入3个字符, 才会弹出下拉列表.ContextKey关于这个属性我有专门的一篇文章介绍, 请参阅ajaxToolkit:AutoCompleteExtender的自定义参数(contextKey)  UseContextKey如果指定了ContextKey参数,  这个属性会被默认置为true, 所以一般不用去管这个参数 , 不过如果因为某种原因程序出了异常-----我就遇到过这种情况, 没有指定ContextKey参数, 但它非要调用包含ContextKey 的形式-----就可以显式地指定这个参数为true 或false.CompletionInterval它的单位是毫秒, 就是用户录入后多长时间, 程序去调用服务来获取数据 , 一般我设这个属性的值为1000.  或不设, 用它默认的值.EnableCaching这是一个要非常小心的属性, 如果把它设为true, 允许缓存, 则, 例如, 我第一次录入1, 返回包括1 的串, 然后我修改了数据源, 再次录入1, 还是返回以前的串,  在调试模式下, 在服务那边下断点, 会看到程序根本没有进来.  也就是说, 对于同样的录入, 控件只获取一次数据, 有多数情况下, 这是有益的, 它可以减少数据访问的次数, 但是在数据源经常变化的情况下, 它就是致命的, 它会向用户提供过时的, 错误的信息.CompletionSetCount这个属性指定一次应该返回多少项, 我们上面没有指定它, 返回了10项,  如果我们希望返回20项, 就指定它为20 即可.CompletionListCssClass,  CompletionListItemCssClass 和 CompletionListHighlightedItemCssClass背景样式, 条目样式, 和鼠标悬念时所指向的条目的样式.DelimiterCharacters如果允许一次选中多项, 中间的分隔符 , 我个人感觉这个很容易造成混乱, 最好把它的值设成空, 也就是不允许选中多项.FirstRowSelected是否默认选中第一项.</pre>    </form></body></html>
webservice

using BusinessLogic;using Model;using System;using System.Collections.Generic;using System.Data;using System.Linq;using System.Web;using System.Web.Services;using Unisoft.ICS.Utility.Data;using Utility.Web;namespace SasSystem.AjaxService{    /// <summary>    /// AjaxAutoCompleteExtender 的摘要说明    /// </summary>    [WebService(Namespace = "http://tempuri.org/")]    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]    [System.ComponentModel.ToolboxItem(false)]    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。     [System.Web.Script.Services.ScriptService]    public class webservice : System.Web.Services.WebService    {        /// <summary>           /// AutoCompleteExtender搜索显示结果集的ServiceMethod           /// </summary>           /// <param name="prefixText">输入的文本,根据这个和数据库进行匹配</param>           /// <param name="count">返回的结果集的长度</param>           /// <param name="contextKey">        /// 传入userName,loginName,经过算法处理后,筛选条件拼接为:userName like '%a%' or loginName like '%a%'        /// AutoCompleteExtender.ContextKey的值,在调用本方法之前可以将其设置为用户的自定义值。重载函数中没有此项参数        /// </param>           /// <returns></returns>           [WebMethod]        public string[] GetAutoCompleteExtenderData(string prefixText, int count, string contextKey)        {            string[] inputSplit = contextKey.Split(',');            contextKey = string.Empty;            foreach (string item in inputSplit)            {                contextKey += ((contextKey != string.Empty ? " or " : "") + (item + " like '%" + prefixText + "%'"));            }            oa_user userBL = new oa_user();            List<oa_user_Info> list = userBL.SelectMany("userID", contextKey, count);            if (list == null || list.Count <= 0)            { return null; }            List<string> items = new List<string>(count);            for (int i = 0; i < list.Count; i++)            {                items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(list[i].userName, list[i].userId.ToString()));            }            return items.ToArray();        }    }}
查询存储过程

CREATE PROCEDURE [dbo].[usp_Common_Sel_Table]-- Add the parameters for the stored procedure here  @TableName nvarchar(128) ,@SelectorString nvarchar(500) = '*' ,@SortExpression nvarchar(200) ,@FilterString nvarchar(2000) ,@TopCount int = 0ASBEGIN-- SET NOCOUNT ON added to prevent extra result sets from-- interfering with SELECT statements.SET NOCOUNT ON;    -- Insert statements for procedure hereDECLARE @Filter NVARCHAR(2050);DECLARE @SqlString NVARCHAR(4000);DECLARE @SortExp NVARCHAR(250);DECLARE @SelectTop NVARCHAR(20);IF @FilterString is NULL or @FilterString = ''BEGINSET @Filter = ''ENDELSEBEGINSET @Filter = ' WHERE ('+ @FilterString +') 'ENDIF @SortExpression is NULL or @SortExpression = ''BEGINSET @SortExp = ''ENDELSEBEGINSET @SortExp = ' ORDER BY ' + @SortExpressionENDIF @TopCount > 0BEGINSET @SelectTop = ' TOP('+Cast(@TopCount as Nvarchar)+') 'ENDELSEBEGINSET @SelectTop = ''END/* Specify the parameter format one time. */SET @SqlString = N'SELECT ' + @SelectTop + ' ' + @SelectorString + ' FROM  [' + @TableName + '] ' + @Filter + '' + @SortExp --PRINT @SqlStringEXECUTE sp_executesql @SqlStringEND


1 0