Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a Json label/value pair from C# Controller Action for jQuery AutoComplete

I need to create a jQuery Autocomplete textbox that gets a list of names from the DB, and when selected, sends the user to the appropriate page link.

I'm trying to do something just like this post: Fire a controller action from a jQuery Autocomplete selection

The solution makes sense, and the click and redirect works, but I don't know how to return more than just a string list of names.

Current controller code (snippet):

        List<string> Names = new List<string>();
        foreach (Child c in listfromDB)
        {
            Names.Add(c.Name);
            //childNames.Add(new KeyValuePair<string, int>(c.Name, c.ID));
        }
        return Json(Names);

The KeyValuePair didn't seem to work. How do I create an object array instead?

My jQuery code:

$(document).ready(function () {
$("#find-child-box").autocomplete({
source: function (request, response) {
    // define a function to call your Action (assuming UserController)
    $.ajax({
        url: '/Admin/AutoCompleteMyChildren', type: "POST", dataType: "json",

        // query will be the param used by your action method
        data: { query: request.term },
        success: function (data) {
            response($.map(data, function (item) {
                return { label: item, value: item };
            }))
        }
    })
},
minLength: 1, // require at least one character from the user
select: function(event, ui) {
alert('mom');
    window.location.href = ui.item.value;
}
}); 
});
like image 580
scojomodena Avatar asked Sep 27 '12 22:09

scojomodena


Video Answer


1 Answers

Actually, autocomplete works fine with a source that returns just an array of strings. This should work fine for you, without modifying your controller action:

JavaScript:

$(document).ready(function () {
    $("#find-child-box").autocomplete({
        source: function (request, response) {
            // define a function to call your Action (assuming UserController)
            $.ajax({
                url: '/Admin/AutoCompleteMyChildren', 
                type: "POST", 
                dataType: "json",
                // query will be the param used by your action method
                data: { query: request.term },
                success: response
            });
        },
        minLength: 1, // require at least one character from the user
        select: function(event, ui) {
            alert(ui.item.ID);
            window.location.href = ui.item.value;
        }
    }); 
});

Check the overview tab of jQueryUI autocomplete to see what kind of data the widget expects.

Per your comment:

As @Alex hints at you'll have to change the data the controller action. You could create the correct object array using something like:

return Json(listfromDB.Select(c => new { label = c.Name, ID = c.ID }));

Which should generate JSON looking like this:

[{ label: 'Scott', ID: '1234' }, ...]

Which autocomplete can use correctly. Then, any time ui.item is available inside of autocomplete's event handlers (select for example), you should be able to access ui.item.ID.

like image 184
Andrew Whitaker Avatar answered Nov 15 '22 07:11

Andrew Whitaker