一直期待ATLAS能夠提供AutoComplete的擴充特性,終於不負眾望,在最新版的ASP.NET AJAX Control Toolkit 已經包含了這個特性:AutoCompleteExtender。使用起來是很簡單的。
以下舉個股票代號查詢的例子,輸入部分代碼、拼音縮寫或者漢字,便能得到全部的提示。
1 添加一個TextBox
<asp:TextBox runat="server" ID="txtStockKeyName" Width="300" autocomplete="off" />
2 添加AutoCompleteExtender,並設定參數
<cc1:AutoCompleteExtender
runat="server"
ID="autoComplete1"
TargetControlID="txtStockKeyName"
ServicePath="StockCode.asmx"
ServiceMethod="GetStockList"
MinimumPrefixLength="1"
CompletionInterval="1000"
EnableCaching="true"
CompletionSetCount="12"
/>
參數說明:
TargetControlID : 輸入查詢關鍵字的文字框
ServicePath : 對應背景Webservice的地址
ServiceMethod : 對應背景Webservice的方法名
MinimumPrefixLength :查詢關鍵字長度產生自動完成的最短長度
CompletionInterval :查詢結果顯示間隔時間(毫秒)
EnableCaching : 啟用Cache
CompletionSetCount :顯示查詢結果的條數
3 根據查詢關鍵字返回查詢結果的Webservice方法
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Collections.Generic;
using System.Collections;
/**//// <summary>
/// StockCode 的摘要說明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class StockCode : System.Web.Services.WebService {
public StockCode () {
//如果使用設計的組件,請取消注釋以下行
//InitializeComponent();
}
[WebMethod]
public string[] GetStockList(string prefixText, int count)
{
if (count == 0)
{
count = 10;
}
Random random = new Random();
List<string> items = new List<string>(count);
for (int i = 0; i < stockID.Length; i++)
{
if (
(stockID[i].IndexOf(prefixText) >= 0)
|| (stockName[i].IndexOf(prefixText) >= 0)
|| (stockPY[i].ToUpper().IndexOf(prefixText.ToUpper()) >= 0)
)
{
items.Add(stockID[i] + ":" + stockName[i]);
}
}
return items.ToArray();
}
//股票代號
string[] stockID = { "610001", "610002", "611003", "611004" };
//股票拼音簡稱
string[] stockPY = { "xg", "ng", "xj", "xc" };
//股票名稱
string[] stockName = { "西瓜", "南瓜", "香蕉", "香腸" };
}
:
範例程式碼:
/Files/heekui/StockID.rar
運行環境:
VS2005 + ASP.NET AJAX V 1.0 + ASP.NET AJAX Control Toolkit