今天做了一下午终于把这个效果(仿百度智能提示功能)做好了,由于偶才接触AJAX技术,所以做这个还是花费了一些时间,不收获还是可以,厚积薄发。。。。不说多了 先看一下代码 呵呵
前台代码:
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="TextBox1"
MinimumPrefixLength="1" ServiceMethod="GetProductName" ServicePath="WebService.asmx">
</cc1:AutoCompleteExtender>
</div>
后台WebService代码:
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Services;//关键程序集引用
using System.Collections.Generic;//关键程序集引用
/// <summary>
/// WebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService()]//一定要添加
public class WebService : System.Web.Services.WebService {
public WebService () {
//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}
[WebMethod]
[ScriptMethod]
public string[] GetProductName(string prefixText, int count)
{
List<string> suggestions=new List<string>();//声明一泛型集合
SqlConnection con = new SqlConnection("server=.;database=NorthWind;uid=sa;pwd=;");
con.Open();
SqlCommand com = new SqlCommand("select distinct productname from Products where productname like @prefixname order by productname", con);
com.Parameters.Add("@prefixname",SqlDbType.NVarChar).Value=prefixText + "%";
SqlDataReader sdr = com.ExecuteReader();
while (sdr.Read())
{
suggestions.Add(sdr.GetString(0));
}
sdr.close();
con.close();
return suggestions.ToArray();
}
}