jQuery的 - 在使用自动完成功能键/值对 [英] jQuery - Use key/value pair in autocomplete

查看:100
本文介绍了jQuery的 - 在使用自动完成功能键/值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ASP MVC视图,我传递一个键/值对从控制器回来。看着提琴手和查看在Google Chrome的调试之后,我可以看到的信息被传递回正常。

In my ASP MVC view, I am passing a key/value pair back from the controller. After looking at fiddler and viewing in Chrome's debugger I can see that the information is being passed back correctly.

我想为键/值对要显示在该自动完成列表。当用户从列表中选择一个项目,我想这个项目的放置在文本框中。

I would like for the value of the key/value pair to be the item that is displayed in the autocomplete list. When the user selects an item from the list, I would like that item's key to be placed into the text box.

下面是jQuery的code从我的观点

Here is the jQuery code from my view

$(function () {
    $('#DRMCompanyId').autocomplete({
        source: '@Url.Action("compSearch", "AgentTransmission")',
        minLength: 2,
        select: function (event, ui) {
            $('#DRMCompanyId').val(ui.item.label);
        }
    });
});

一件事我注意到 - 如果我在浏览器的调试器添加 UI 变量来观察名单我注意到,标签和值是完全一样的。然而,再次,我看到了什么东西被返回是一个完整的键/值对。

One thing I noticed - if I add the ui variable to the watch list in the browser's debugger I notice that the label and the value are the exact same. Again, however, I'm seeing that what's being returned is the complete key/value pair.

下面是网络/响应控制台的屏幕截图搜索完成后。有些数据是私有的,所以我涂黑它,但是你可以看到有返回键/值对。

Here is a screen shot of the Network/Response console after the search is complete. Some of the data is private so I blacked it out however you can see there is a key/value pair being returned.

推荐答案

您需要做Ajax请求自己和数据转换到jQueryUI的预期格式为:

You'll need to make the AJAX request yourself and transform the data to the format that jQueryUI expects:

$(function () {
    $('#DRMCompanyId').autocomplete({
        source: function (request, response) {
           $.ajax({
               url: '@Url.Action("compSearch", "AgentTransmission")',
               type: 'GET',
               dataType: 'json',
               data: request,
               success: function (data) {
                   response($.map(data, function (value, key) { 
                        return {
                            label: value,
                            value: key
                        };
                   }));
               }
           });
        },
        minLength: 2
    });
});

另外,自动完成项目的属性自动放置在输入选择了该项目时,所以应该不需要自定义的选择处理程序。

Also, the value property of an autocomplete item is automatically placed in the input when that item is selected, so there should be no need for a custom select handler.

示例: http://jsfiddle.net/Aa5nK/60/

这篇关于jQuery的 - 在使用自动完成功能键/值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆