Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
638 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - jQuery - Use key/value pair in autocomplete

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.

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

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.

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Example: http://jsfiddle.net/Aa5nK/60/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...