选择自动完成文本时调用函数

时间:2018-07-17 15:16:50

标签: c# asp.net webforms

您好,我确实为我的项目构建了一个自动填充文本字段:

HTML编码:

@Input() input: string; // undefined by default

C#背后的代码:

<!-- Autocomplete Function -->
<ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender"  runat="server" CompletionSetCount="10" TargetControlID="input_source" 
ServiceMethod="GetCompletionList" CompletionInterval="100" EnableCaching="false" MinimumPrefixLength="1"> 
</ajaxToolkit:AutoCompleteExtender>

 <!--Inputfield Autocomplete-->
 <asp:TextBox autocomplete="on" id="input_source" OnTextChanged="input_source_TextChanged" runat ="server"  class="form-control" placeholder="Please enter"></asp:TextBox>  

现在,我想每次从自动完成功能中选择建议时都调用以下功能。这样可能吗?

//Autocomplete Field
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetCompletionList(string prefixText, int count)
{
    using (SqlConnection con = new SqlConnection())
    {
        con.ConnectionString = lr_sqlserver;


        using (SqlCommand com = new SqlCommand())
        {
            com.CommandText = "SELECT TOP 5 Source FROM" + " " + selected_table + " " + "WHERE Source like '%' + @Search + '%'";

            com.Parameters.AddWithValue("@Search", prefixText);
            com.Connection = con;
            con.Open();
            List<string> suggestions = new List<string>();
            using (SqlDataReader sdr = com.ExecuteReader())
            {
                while (sdr.Read())
                {
                    suggestions.Add(sdr["Source"].ToString());
                }
            }
            con.Close();
            return suggestions;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您需要将TextBox放在UpdatePanel内,并在TextBox上设置AutoPostBack =“ True”

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:TextBox autocomplete="on" id="input_source" OnTextChanged="input_source_TextChanged" runat ="server"  class="form-control" placeholder="Please enter" AutoPostBack="True"></asp:TextBox> 
    </ContentTemplate>
</asp:UpdatePanel>