AJAX中利用AutoCompleteExtender实现类似于谷歌的智能提示(利用记事本)

1、打开VS,添加TextFile1.txt、WebForm1.aspx、WebService1.asmx;

2、在TextFile1.txt添加如下图所示数据:

3、在WebService1.asmx中添加GetCompleteList方法,代码如下:

GetCompleteList方法
 [WebMethod]
        public String[] GetCompleteList(string prefixText, int count)
        {
            if (autoCompleteWordList == null)
            {
                string[] temp = File.ReadAllLines(Server.MapPath("./TextFile1.txt"));
                Array.Sort(temp, new CaseInsensitiveComparer());
                autoCompleteWordList = temp;
                int index = Array.BinarySearch(autoCompleteWordList, prefixText, new CaseInsensitiveComparer());
                if (index < 0)
                {
                    index = ~index;
                }
                int matchingCount;
                for (matchingCount = 0; matchingCount < count && index + matchingCount < autoCompleteWordList.Length; matchingCount++)
                {
                    if (!autoCompleteWordList[index + matchingCount].StartsWith(prefixText, StringComparison.CurrentCultureIgnoreCase))
                    {
                        break;
                    }
                }
                String[] returnValue = new string[matchingCount];
                if (matchingCount > 0)
                {
                    Array.Copy(autoCompleteWordList, index, returnValue, 0, matchingCount);
                }
                return returnValue;
            }
            else
            {
                autoCompleteWordList = null;
                return null;
            }
        }

4、在WebForm1.aspx窗体中添加源码:

WebForm1.aspx源码
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <p class="style1">省份智能提示:</p>
        <asp:TextBox ID="TextBox1" runat="server" Height="18px" Width="184px"></asp:TextBox>
        <br />
        <asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" ServiceMethod="GetCompleteList"
         ServicePath="~/WebService1.asmx" Enabled="true" MinimumPrefixLength="1" CompletionSetCount="8" TargetControlID="TextBox1">
        </asp:AutoCompleteExtender>
    </div>
    </form>
</body>

5、在浏览器中查看如图:

posted @ 2012-11-19 17:47  zwy_net  阅读(400)  评论(0编辑  收藏  举报