AJAX 实现自动完成功能

 

自动功能类似GOOGLE。如下图:

                                                

 

需要添加的控件有:

                                               AJAX 实现自动完成功能_第1张图片

 

ScriptManager控件,AutoCompleteExtender控件。

添加Web Service。

[WebService(Namespace = "http://tempuri.org/")] 



[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 



[System.Web.Script.Services.ScriptService()] 



public class AutoCompleteService : System.Web.Services.WebService 



{



    public AutoCompleteService ()



 {        



 //InitializeComponent();     



}



 private static string[] m_autoCompleteWordList = null; 

 [WebMethod]  

public String[] GetWordList(string prefixText, int count) 

 {   if(m_autoCompleteWordList == null)  

 {    string[] temp = File.ReadAllLines(Server.MapPath("~/TextFile/SuggestWords.txt"));   

 Array.Sort(temp,new CaseInsensitiveComparer());  

  m_autoCompleteWordList = temp;   }



  int index = Array.BinarySearch(m_autoCompleteWordList, prefixText,           new CaseInsensitiveComparer());  

 if (index < 0)   {    index = ~index;   }



  int matchingCount;  

 for (matchingCount = 0; matchingCount < count &&    index + matchingCount < m_autoCompleteWordList.Length;   matchingCount++)  

 {    

if(!m_autoCompleteWordList[index+matchingCount].StartsWith(prefixText,StringComparison.CurrentCultureIgnoreCase))    

 break;   }



  String [] returnValue = new string[matchingCount];  

 if (matchingCount > 0)  

 {    Array.Copy(m_autoCompleteWordList,index,returnValue,0,matchingCount);   }



  return returnValue; 

 }



} 



在设计页面中设置Autocompleteextender控件:

<cc1:autocompleteextender id="AutoCompleteExtender1" runat="server" targetcontrolid="suggestedInput"   ServicePath="WebServer/AutoCompleteService.asmx" ServiceMethod="GetWordList"></cc1:autocompleteextender>

运行结果:

                                                      

你可能感兴趣的:(AJAX 实现自动完成功能)