AJAX自动完成不能在用户控件内部工作为什么?

时间:2014-11-25 12:33:33

标签: asp.net ajax

我的AJAX自动完成功能不能与用户控件一起使用,但是当我将它与普通的ASP.NET页面一起使用时,它可以正常工作:

[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetCity(string prefixText, string contextKey)
{

    DataTable dt = new DataTable();
    string constr = ConfigurationManager.ConnectionStrings["ERPConnection"].ToString();
    SqlConnection con = new SqlConnection(constr);
    con.Open();
    string CmdText = "select name+ '-' + ' ['+CONVERT(VARCHAR, custid) +']'as name from ht_cust where name like @City+'%' and EmpID =@EmpId";
    SqlCommand cmd = new SqlCommand(CmdText, con);
    cmd.Parameters.AddWithValue("@City", prefixText);
    cmd.Parameters.AddWithValue("@EmpId", contextKey);
    SqlDataAdapter adp = new SqlDataAdapter(cmd);
    adp.Fill(dt);
    List<string> CityNames = new List<string>();
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        CityNames.Add(dt.Rows[i][0].ToString());
    }

    return CityNames;
}

aspx code
<asp:UpdatePanel ID="UpdatePanel7" runat="server">
    <ContentTemplate>
        <asp:TextBox ID="txtCity" runat="server" UseContextKey="true" onkeyup="SetContextKey()" CssClass="input-1" Width="200px"></asp:TextBox>  
        <ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="txtCity" MinimumPrefixLength="1" EnableCaching="true" CompletionSetCount="1" CompletionInterval="1000" ServiceMethod="GetCity" UseContextKey="true" CompletionListCssClass="autocomplete_completionListElement">
        </ajaxToolkit:AutoCompleteExtender>
     </ContentTemplate>
</asp:UpdatePanel>

1 个答案:

答案 0 :(得分:1)

您无法通过用户控件调用webmethod,因为它会自动在页面内呈现。将您的webmethod移至aspx页面。

如果您想要控制器内的逻辑,那么您可以从aspx页面调用它,但您的webmethod需要在aspx页面。

示例:

在aspx页面中:

[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetCity(string prefixText, string contextKey)
{
  return mycontrol.GetCity(prefixText, contextKey);
}

在您的用户控件中:

public static List<string> GetCity(string prefixText, string contextKey)
{

    DataTable dt = new DataTable();
    string constr = ConfigurationManager.ConnectionStrings["ERPConnection"].ToString();
    SqlConnection con = new SqlConnection(constr);
    con.Open();
    string CmdText = "select name+ '-' + ' ['+CONVERT(VARCHAR, custid) +']'as name from ht_cust where name like @City+'%' and EmpID =@EmpId";
    SqlCommand cmd = new SqlCommand(CmdText, con);
    cmd.Parameters.AddWithValue("@City", prefixText);
    cmd.Parameters.AddWithValue("@EmpId", contextKey);
    SqlDataAdapter adp = new SqlDataAdapter(cmd);
    adp.Fill(dt);
    List<string> CityNames = new List<string>();
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        CityNames.Add(dt.Rows[i][0].ToString());
    }

    return CityNames;
}