Anamnian Anamnian - 3 months ago 13
Ajax Question

Mvc autocomplete ajax

Try to:

$(document).ready(function () {
$('#cityName').autocomplete({
source: function(request,response) {
$.ajax({
type: 'POST',
url: '@Url.Action("Search", "City")',
dataType: 'json',
data: { name: request.term } ,
success: function (data) {
response($.map(data, function (item) {
alert(JSON.stringify(data));
alert(JSON.stringify(item.name));
return {
name: item.name,
label: item.name
}
}));
}
})
},
messages: {
noResults: "", results: ""
}
})
})


In
alert(JSON.stringify(data))
got this: {"items":["Boston","Berlin"]}.
In
alert(JSON.stringify(item.name))
got this: undefined.

Question: how do it (item.name) works?

Answer

You have to just return array of strings:

$(document).ready(function () {
        $('#cityName').autocomplete({
            source: function(request,response) {
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("Search", "City")',
                    dataType: 'json',
                    data: { name: request.term } ,
                    success: function (data) {
                        response(data.items);
                    }
                })
            },
            messages: {
                noResults: "", results: ""
            }
        })
    })
Comments