ajaxToolkit 是微軟官方的一個ajax控件包, AutoCompleteExtender 就是其中之一. 需要引用ajaxToolkit.dll
達到的效果就是像baidu的輸入查詢條件帶出提示的效果。
前臺文本框:
<asp:TextBox ID="txt1" runat="server"></asp:TextBox>
這就是一個默認的文本框, 不需要任何多餘的設定. 然後定義一個AutoCompleteExtender, 這裏我們只設置了最基本的選項, 其它的選項後面我會說明:
<ajaxToolkit:AutoCompleteExtender ID="ac1" runat="server" TargetControlID="txt1" ServicePath="webservice.asmx" // 這邊放的是webservice名字 ServiceMethod="GetTextList" MinimumPrefixLength="1" ></ajaxToolkit:AutoCompleteExtender>
這樣 , 前臺的工作就完成了。
後臺要添加一個webservice服務。
namespace AJAXEnabledWebApplication3
{
/// <summary>
/// Summary description for AutoComplete
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
[ToolboxItem(false)]
public class AutoComplete : System.Web.Services.WebService
{
public static string[] autoCompleteTextList = null;
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public string[] GetTextList(string prefixText, int count)
{ ///檢測參數是否爲空
if (string.IsNullOrEmpty(prefixText) == true || count <= 0) return null;
if (autoCompleteTextList == null)
{
//獲取data.txt文件的數據
StreamReader reader = new StreamReader(Server.MapPath("data.txt"));
//按行方式讀取data.txt文件的數據
ArrayList list = new ArrayList();
string rowString = reader.ReadLine();
while (rowString != null)
{ ///讀取一行
list.Add(rowString);
rowString = reader.ReadLine();
}
reader.Close();
//將獲取的內容保存到臨時數組中
string[] tempTextList = new string[list.Count];
int i = 0;
foreach (string s in list)
{
tempTextList[i++] = s;
}
//對數組進行排序
Array.Sort(tempTextList, new CaseInsensitiveComparer());
autoCompleteTextList = tempTextList;
}
//定位二叉樹搜索的起點
int index = Array.BinarySearch(autoCompleteTextList, prefixText, new CaseInsensitiveComparer());
if (index < 0)
{
//修正起點
index = ~index;
}
//搜索符合條件的數據
int matchCount = 0;
for (matchCount = 0; matchCount < count && matchCount + index < autoCompleteTextList.Length; matchCount++)
{
//查看開頭字符串相同的項
if (autoCompleteTextList[index + matchCount].StartsWith(prefixText, StringComparison.CurrentCultureIgnoreCase) == false)
{ break; }
}
//處理搜索結果
string[] matchResultList = new string[matchCount];
if (matchCount > 0)
{
//複製搜索結果
Array.Copy(autoCompleteTextList, index, matchResultList, 0, matchCount);
}
return matchResultList;
}
}
}
這樣就可以瀏覽效果了