我正在尝试使用Ajax AutoCompleteExtender,但它无法正常工作。我哪里错了。其他Ajax控件,如更新面板,工作正常。使用Chrome。
ASPX:
<asp:TextBox ID = "txtSearch" runat="server">
<ajax:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
TargetControlID="txtSearch" MinimumPrefixLength="2" EnableCaching="true"
CompletionSetCount="10" CompletionInterval="1000" ServiceMethod="GetCountries">
</ajax:AutoCompleteExtender>
ASPX.CS
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static IEnumerable<string> GetCountries()
{
return objDAL.GetCountries(txtSearch.Text.Trim());
}
DAL:
public IEnumerable<string> GetCountries(string text)
{
return MyDB.tblCountries.Where(e=>e.CountryName.StartsWith(text)).
Select(e=>e.CountryName);
}
也试过
public static List<string> GetCountries()
{
return objDAL.GetCountries(txtSearch.Text.Trim()).ToList();
}
答案 0 :(得分:1)
使用此代码:
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Ajax AutoCompleteExtender without Webservice</title>
</head>
<body>
<form id="form1" runat="server">
<ajax:ToolkitScriptManager ID="ScriptManager1" runat="server"/>
<div>
<asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
<ajax:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="txtCountry"
MinimumPrefixLength="1" EnableCaching="true" CompletionSetCount="1" CompletionInterval="1000" ServiceMethod="GetCountries" >
</ajax:AutoCompleteExtender>
</div>
</form>
</body>
</html>
代码背后:
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Configuration;
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetCountries(string prefixText)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("select * from Country where CountryName like @Name+'%'", con);
cmd.Parameters.AddWithValue("@Name", prefixText);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
List<string> CountryNames = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
CountryNames.Add(dt.Rows[i][1].ToString());
}
return CountryNames;
}