我希望在c#中使用javascript和数据库驱动数据库驱动的自动完成文本框

时间:2013-02-19 11:37:50

标签: 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
    {
        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()函数无效。

1 个答案:

答案 0 :(得分:-1)

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

 $(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
            });
        });
});

您可以创建一个web方法,也可以像我一样使用Web服务

Webservices代码:

[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();
    }
}

希望这对你有用。