当用户在输入网站地址的文本框中输入的时候会自动弹出一个下拉菜单,显示最近查询过的网站,并不断根据输入文本的内容缩小范围。比如:当输入“w”的时候,会列出所有w开头的网址,当输入到“www.f”的时候,就只显示www.felixwoo.com了。当点击下拉菜单中的一个网址后,会自动完成文本框中的内容。整个过程和IE的地址栏效果类似。显示效果如图
这个功能是通过ASP.NET AJAX AutoCompleteExtender实现的,只需要几行代码即可搞定。<BR>首先需要在页面上添加asp:AutoCompleteExtender标记,别忘了之前要有asp:ScriptManager的声明。
<DIV class=code><asp:ScriptManager ID="ScriptManager" runat="server" /><BR><asp:AutoCompleteExtender ID="AutoCompleteExtender1" TargetControlID="searchtext"<BR>runat="server" ServiceMethod="GetCompletionList"<BR>ServicePath="~/SearchAutoComplete.asmx" MinimumPrefixLength="1" /></DIV>其中TargetControlID为输入网址的文本框的ID,ServicePath为得到网站列表的webservice地址,ServiceMethod即那个webservice中的具体方法,MinimumPrefixLength=1意思是当输入一个字符的时候即开始提示。<BR><BR>在SearchAutoComplete.asmx中要做的就是从数据库中返回最近查询过的网站,并通过prefixText参数来过滤出只以prefixText开头的网站,这样才能实现逐级提示的功能。SearchAutoComplete.asmx代码如下:<BR>
<DIV class=code>[WebMethod] <BR>public string[] GetCompletionList(string prefixText, int count) <BR>{ <BR> List<string> list = DataProvider.GetURLList();<BR> foreach (string s in list) <BR> { <BR> if (s.StartsWith(prefixText)) <BR> { <BR> list.Add(s); <BR> } <BR> } <BR> return list.ToArray(); <BR>} </DIV><BR>其中List<string> list是声明的了一个string的范型,这个是.net 2.0中新增的功能,避免了原来使用ArrayList带来的装箱和拆箱的性能消耗。DataProvider.GetURLList()从从数据库返回所有网站列表,返回类型自然也是List<string>。其他的代码都很简单,相信一看就明白了。<BR><BR></div>
<DIV class=code><asp:ScriptManager ID="ScriptManager" runat="server" /><BR><asp:AutoCompleteExtender ID="AutoCompleteExtender1" TargetControlID="searchtext"<BR>runat="server" ServiceMethod="GetCompletionList"<BR>ServicePath="~/SearchAutoComplete.asmx" MinimumPrefixLength="1" /></DIV>其中TargetControlID为输入网址的文本框的ID,ServicePath为得到网站列表的webservice地址,ServiceMethod即那个webservice中的具体方法,MinimumPrefixLength=1意思是当输入一个字符的时候即开始提示。<BR><BR>在SearchAutoComplete.asmx中要做的就是从数据库中返回最近查询过的网站,并通过prefixText参数来过滤出只以prefixText开头的网站,这样才能实现逐级提示的功能。SearchAutoComplete.asmx代码如下:<BR>
<DIV class=code>[WebMethod] <BR>public string[] GetCompletionList(string prefixText, int count) <BR>{ <BR> List<string> list = DataProvider.GetURLList();<BR> foreach (string s in list) <BR> { <BR> if (s.StartsWith(prefixText)) <BR> { <BR> list.Add(s); <BR> } <BR> } <BR> return list.ToArray(); <BR>} </DIV><BR>其中List<string> list是声明的了一个string的范型,这个是.net 2.0中新增的功能,避免了原来使用ArrayList带来的装箱和拆箱的性能消耗。DataProvider.GetURLList()从从数据库返回所有网站列表,返回类型自然也是List<string>。其他的代码都很简单,相信一看就明白了。<BR><BR></div>
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1925472