在自动填充上显示多条记录

时间:2012-06-21 17:57:08

标签: asp.net sql autocomplete jquery-autocomplete

我有一个带有JQuery的ASP.NET文本框自动完成功能,工作正常,我输入了人名的一部分,并显示了包含所有可能选项的列表,但现在我希望当我搜索名称时显示我在列表中结果名称旁边的电子邮件地址,名称和电子邮件在SQL数据库上,我希望当我输入John时,我会得到列表

John Andrews John@email.com

John Smith Smith@email.com

等等......这是代码:

  <%@ WebHandler Language="C#" Class="Search_CS" %>
    using System;
    using System.Web;
    using System.Data.SqlClient;
    using System.Configuration;
    using System.Text;

    public class Search_CS : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        string prefixText = context.Request.QueryString["q"];
        using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = ConfigurationManager
                    .ConnectionStrings["constr"].ConnectionString;
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "select * from directory where name like @SearchText + '%'";
                cmd.Parameters.AddWithValue("@SearchText", prefixText);
                cmd.Connection = conn;
                StringBuilder sb = new StringBuilder(); 
                conn.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        sb.Append(sdr["name"])
                            .Append(Environment.NewLine);
                    }
                }
                conn.Close();
                context.Response.Write(sb.ToString()); 
            }
        }
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
    }

2 个答案:

答案 0 :(得分:1)

jQuery autocomplete允许您显示两个字段。 为此,您应该使用jsonp数据源:

请看这里demo

要获取您的json数据,您必须将IHttpHandler更改为输出json

为此,您需要创建一个对象列表,并使用JavaScriptSerializer将其序列化为json。

例如:

//myList = your list of objects with name and email.
JavaScriptSerializer serializer = new JavaScriptSerializer();
string jsonString = serializer.Serialize(myList);

答案 1 :(得分:0)

当您为字符串构建器添加名称时,还要添加电子邮件..此代码应该可以使用

while (sdr.Read())
{
    sb.Append(sdr["name"] + " " + sdr['email']).Append(Environment.NewLine);
}

while (sdr.Read())
{
    sb.Append(sdr["name"])
    sb.Append(" ") //space between name and email
    sb.Append(sdr['email'])
    sb.Append(Environment.NewLine);
}