文章目錄
以前見到google和迅雷等網站在搜尋文字框中輸入文字後能自動提示,感覺這種功能很炫也很實用.現在在學習asp.net ajax 發現AjaxControlToolKit工具包中的AutoComplete控制項就能實現這種功能,而且非常簡單。
簡介
AutoComplete控制項就是在使用者在文字框輸入前幾個字母或是漢字的時候,該控制項就能從存放資料的文或是資料庫裡將所有以這些字母開頭的資料提示給使用者,供使用者選擇,提供方便.
重要屬性
TargetControlID:指定要實現提示功能的控制項。
ServicePath:WebService的路徑,提取資料的方法是寫在一個WebService中的。
ServeiceMethod:寫在WebService中的用於提取資料的方法的名字。
MinimumPrefixLength:用來設定使用者輸入多少字母才出現提示效果。
CompletionSetCount:設定提示資料的行數。
CompletionInterval:從伺服器擷取書的時間間隔,單位是毫秒。
樣本
開啟vs2005建立一個AjaxControlToolKit網站。
在網站的App_Data檔案夾下添加文字檔TextFile.txt,並在其中添加資料,如下
在網站的根目錄下添加一個Web服務,命名為oec2003_AutoComplete,系統自動將Web服務兩個部分,設計部分oec2003_AutoComplete.asmx和代碼部分oec2003_AutoComplete.cs,其中oec2003_AutoComplete.cs檔案自動放入到App_Code目錄下。開啟oec2003_AutoComplete.cs檔案,添加擷取資料的方法GetCompleteList,代碼如下:
using System; using System.Web; using System.Collections; using System.Web.Services; using System.Web.Services.Protocols; using System.IO; /// <summary>/// AutoComplete 的摘要說明/// </summary>[WebService(Namespace = "http://tempuri.org/")][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)][System.Web.Script.Services.ScriptService]public class AutoComplete : System.Web.Services.WebService{ public AutoComplete() { //如果使用設計的組件,請取消注釋以下行 //InitializeComponent(); } [WebMethod] public string HelloWorld() { return "Hello World"; } /// <summary> /// 擷取資料的方法GetCompleteList /// </summary> //定義靜態數組用於儲存擷取的資料 private static string[] autoCompleteWordList = null; [WebMethod] public String[] GetCompleteList(string prefixText, int count) { if (autoCompleteWordList == null) { string[] temp = File.ReadAllLines(Server.MapPath("~/App_Data/TextFile.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; }}
由於在上面的代碼中使用了File類,所以應該添加如下代碼:
using System.IO;
因為需要在用戶端調用Web服務,還需要添加如下代碼
[System.Web.Script.Services.ScriptService]
儲存Web 服務的代碼
開啟根目錄下預設產生的Default.aspx,在頁面中拖拽一個TextBox控制項和一個AutoCompleteExtender控制項。在屬性視窗設定AutoCompleteExtender控制項的屬性,如下
<ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" ServiceMethod="GetCompleteList" ServicePath="oec2003_AutoComplete.asmx" Enabled="true" MinimumPrefixLength="2" CompletionSetCount="10" TargetControlID="TextBox1"></ajaxToolkit:AutoCompleteExtender>
在Web服務中的count參數的值是取CompletionSetCount屬性的值。
儲存設計的頁面,將預設版面設定為起始頁,按F5運行後在文字框中輸入oe,就能看到想要的結果。
代碼下載