0

我正在使用 jQuery AutoComplete 根据输入的值从数据库中获取结果。然后,用户将单击搜索按钮以告诉页面搜索该特定条目的详细信息。

我想获得 2 个值,NameTitle。我只想向用户显示名称,而页面使用标题作为搜索条件。

例如:当一个人输入Vehicle时,结果将显示Vehicle1, Vehicle2在一个列表中。
当用户点击时Vehicle1,会出现一个隐藏框,标题会是Bike,比如with Vehicle2,会发出隐藏框Car

我可以让名称正确显示在文本框中,但我无法终生(并且经过 2 天的搜索)将标题绑定到隐藏框。

JavaScript:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $(".tb").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: "AutoComplete.asmx/FetchEmailList",
                        data: "{ 'prefix': '" + request.term + "' }",
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        dataFilter: function (data) { return data; },
                        success: function (data) {
                            response($.map(data.d, function (item) {
                                return {
                                    //value: item.Title,
                                    label: item.Name
                                };
                            }));
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(textStatus);
                        }
                    });
                },
                minLength: 2
            });
        });
    </script>

ASPX 代码:

<div class="ui-widget" >
    <asp:TextBox ID="tbAuto" class="tb" runat="server">
    </asp:TextBox>
    <asp:TextBox runat="server" ID="tbHidden" class="tb"></asp:TextBox>
</div>

代码隐藏:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class AutoComplete : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Employee> FetchEmailList(string prefix)
{
    var emp = new Employee();
    var fetchEmail = emp.GetEmployeeList(prefix)
    .Where(m => m.Name.ToLower().StartsWith(prefix.ToLower()));
    return fetchEmail.ToList();
}    
}

CompletionClass:(请原谅命名)

public class Employee
{
    public string Title { get; set; }
    public string Name { get; set; }
    public string value { get; set; }

    public List<Employee> GetEmployeeList(string prefixText)
    {
        List<Employee> cmpList = new List<Employee>();

        SqlConnection db = DataConn.SqlConnection();

        db.Open();
        SqlTransaction transaction = db.BeginTransaction();

        //var array = new ArrayList();

        try
        {
            SqlCommand command = new SqlCommand("Select [something] FROM vwGetDetails WHERE [something_else] LIKE N'%" + prefixText + "%' ORDER BY [thatOther_thing] ASC", db, transaction);
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    cmpList.Add(new Employee() { Name = reader["Value1"].ToString(), Title = "Value1_Cat", value = "Value1_Cat"});
                }
            }

            command = new SqlCommand("Select [something] FROM [somewhere] WHERE [thingy] LIKE N'%" + prefixText + "%' ORDER BY [previousThingy] ASC", db, transaction);
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    cmpList.Add(new Employee() { Name = reader["Value2"].ToString(), Title = "Value2_Cat", value = "Value2_Cat"});
                }
            }

            transaction.Commit();
        }
        catch (SqlException)
        {
            transaction.Rollback();
            cmpList.Add(new Employee() { Name = "Problem Getting Results.", value = "Error"});
            //array.Add("Problem Getting Results.");
        }

        if (cmpList.Count == 0)
            cmpList.Add(new Employee() { Name = "Nothing to Display.", value = "Info"});
        //array.Add("Nothing to Display.");

        //return array;

        return cmpList;
    }

}
4

2 回答 2

1

对 JavaScript 的这些修改应该可以解决问题:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $('input[name$="tbAuto"]').autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "AutoComplete.asmx/FetchEmailList",
                    data: "{ 'prefix': '" + request.term + "' }",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataFilter: function (data) { return data; },
                    success: function (data) {
                        response(data.d);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(textStatus);
                    }
                });
            },
            minLength: 2,
            focus: function(event, ui) {
                $('input[name$="tbAuto"]').val(ui.item.Name);
                return false;
            },
            select: function(event, ui) {
                $('input[name$="tbAuto"]').val(ui.item.Name);
                $('input[name$="tbHidden"]').val(ui.item.Title);
                return false;
            }
        }).data('autocomplete')._renderItem = function(ul, item) {
            return $('<li>').data('item.autocomplete', item).append('<a>' + item.Name + '</a>').appendTo(ul);
        };
    });
</script>

这里的假设是选择器准确地返回我们正在处理的元素,如果不是,它们需要调整。

于 2012-10-12T10:29:35.353 回答
0

凉爽的。几天来我一直在谷歌搜索这个解决方案......优秀的干净代码!只是一个小评论:使用 jqueryUI 1.10,这会引发 javascript 异常。 .data('autocomplete')._renderItem = function(ul, item) {... 我用过 .data('ui-autocomplete')._renderItem = function(ul, item) {... ,一切都很好。

于 2013-09-17T11:48:29.867 回答