Jquery 我想要使用javascript和c中的数据库驱动的自动完成文本框

Jquery 我想要使用javascript和c中的数据库驱动的自动完成文本框,jquery,c#-3.0,Jquery,C# 3.0,我想在文本框中列出机场名称,例如在文本框中键入Las时,从数据库中提取机场名称。文本框应该会显示拉斯维加斯 Default.aspx.cs: public string listFilter = null; protected void Page_Load(object sender, EventArgs e) { listFilter = BindName(); } private string BindName() { try { SqlConne

我想在文本框中列出机场名称,例如在文本框中键入Las时,从数据库中提取机场名称。文本框应该会显示拉斯维加斯

Default.aspx.cs:

public string listFilter = null;

protected void Page_Load(object sender, EventArgs e)
{
    listFilter = BindName();
}

private string BindName()
{
    try
    {
        SqlConnection con = new SqlConnection(@"Data Source=172.16.10.170;Initial Catalog=cbtsv;User ID=cbtsv;Password=cbtsvpass;");
        con.Open();
        DataTable ds = new DataTable();
        using (SqlCommand cmd = con.CreateCommand())
        {
            SqlCommand com = new SqlCommand("select SearchKey from DTAirportCity where SearchKey like '%TextBox1.Text%'", con);
            SqlDataAdapter sda = new SqlDataAdapter(com);

            sda.Fill(ds);

        }

        StringBuilder output = new StringBuilder();
        output.Append("[");
        for (int i = 0; i < ds.Rows.Count; ++i)
        {
            output.Append("\"" + ds.Rows[i]["SearchKey"].ToString() + "\"");

            if (i != (ds.Rows.Count - 1))
            {
                output.Append(",");
            }
        }
        output.Append("];");

        return output.ToString();
        con.Close();
    }
    catch (Exception)
    {

        throw;
    }
}
Default.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
 <head runat="server">
 <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
 <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
 <script src="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
 <title></title>
 <script type="text/javascript">
     function LoadList() {
         var dt=null;
     dt = <%=listFilter %>
    }
</script>
</head>
<body>
<form id="form1" runat="server">
<div>

 <asp:TextBox ID="TextBox1" runat="server" OnLoad="LoadList()"></asp:TextBox>    
    <br />

</div>
</form>


问题:-LoadList函数不工作。

请尝试以下代码这是一个工作示例:

 $(document).ready(function () {
        $('[ID$=txtPatientLastname]').live('keyup.autocomplete', function () {

            $(this).autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '<%=ResolveUrl("~/Resources/WebService.asmx/GetPatientLastName") %>',
                        data: "{ 'prefix': '" + request.term + "'}",
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {
                            response($.map(data.d, function (item) {
                                return {
                                    label: item.split('-')[0],
                                    val: item.split('-')[1]
                                }
                            }))
                        },
                        error: function (response) {
                            alert(response.responseText);
                        },
                        failure: function (response) {
                            alert(response.responseText);
                        }
                    });
                },
                select: function (e, i) {
                },
                minLength: 1
            });
        });
});
您可以创建一个webmethod,也可以像我一样使用Web服务

Web服务代码:

[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string[] GetPatientLastName(string prefix)
{
    List<string> customers = new List<string>();
    using (SqlConnection conn = new SqlConnection())
    {
        string connectionstring = CCMMUtility.GetCacheForWholeApplication();
        conn.ConnectionString = connectionstring;
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "select distinct top(10) PatientLastname from tblMessage where  " +
            "PatientLastname  like '%'+ @SearchText + '%' order by PatientLastname";
            cmd.Parameters.AddWithValue("@SearchText", prefix);
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    customers.Add(string.Format("{0}", sdr["PatientLastname"]));
                }
            }
            conn.Close();
        }
        return customers.ToArray();
    }
}

希望这对您有用。

尝试以下代码这是一个有效的示例:

 $(document).ready(function () {
        $('[ID$=txtPatientLastname]').live('keyup.autocomplete', function () {

            $(this).autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '<%=ResolveUrl("~/Resources/WebService.asmx/GetPatientLastName") %>',
                        data: "{ 'prefix': '" + request.term + "'}",
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {
                            response($.map(data.d, function (item) {
                                return {
                                    label: item.split('-')[0],
                                    val: item.split('-')[1]
                                }
                            }))
                        },
                        error: function (response) {
                            alert(response.responseText);
                        },
                        failure: function (response) {
                            alert(response.responseText);
                        }
                    });
                },
                select: function (e, i) {
                },
                minLength: 1
            });
        });
});
您可以创建一个webmethod,也可以像我一样使用Web服务

Web服务代码:

[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string[] GetPatientLastName(string prefix)
{
    List<string> customers = new List<string>();
    using (SqlConnection conn = new SqlConnection())
    {
        string connectionstring = CCMMUtility.GetCacheForWholeApplication();
        conn.ConnectionString = connectionstring;
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "select distinct top(10) PatientLastname from tblMessage where  " +
            "PatientLastname  like '%'+ @SearchText + '%' order by PatientLastname";
            cmd.Parameters.AddWithValue("@SearchText", prefix);
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    customers.Add(string.Format("{0}", sdr["PatientLastname"]));
                }
            }
            conn.Close();
        }
        return customers.ToArray();
    }
}

希望这对你有用。

使用jquery自动完成如何实现。你的意思是你有一个数据库,你想使用该数据库自动完成文本框上的功能使用此链接可能会帮助你使用jquery自动完成如何实现。你的意思是你有一个数据库,你想使用数据库使用此链接可能会有助于您不复制粘贴代码您从链接复制代码并粘贴到其他位置不复制粘贴代码您从链接复制代码并粘贴到此处