My jQuery autocomplete looks like this...
If I do a console.log
statement I can see that each of the list items actually has the key/value pair that I'm looking for however for whatever reason it won't display properly.I use an Ajax call to populate the list here's what the code looks like
Controller
public JsonResult GetDistributorInfo(string term)
{
var banks = from c in db.BankListMaster.Where(n => n.BankName.Contains(term))
select new
{
Key = c.ID,
Value = c.BankName
};
return Json(banks, JsonRequestBehavior.AllowGet);
}
jQuery/Ajax
var tempResults = [];
$(function () {
$('#DisplayDistributor').autocomplete({
source: function (request, response) {
$.ajax({
url: '@Url.Action("GetDistributorInfo", "Agent")',
type: 'GET',
dataType: 'json',
data: request,
success: function (data) {
tempResults = data;
response($.map(data, function (value, key) {
return {
label: value,
value: key
};
}));
},
});
},
minLength: 2,
select: function (event, ui) {
console.log(ui);
$('#DistributorId').val(tempResults[ui.item.key]);
$('#DisplayDistributor').text(tempResults[ui.item.value]);
return false;
}
});
});
The data returned is an array of objects. The value
parameter of your $.map()
call contains the object, and the key
parameter is the index of the item in the array (See the first "overload" here ). So you are setting the object itself as the label
property, which is why it's being displayed as [object Object]
.
Try this:
response($.map(data, function (item, idx) {
return {
label: item.Value,
value: item.Key
};
}));
You are using the item wrongly in the response and select method:
1) Your response should look like:
response($.map(data, function (item) {
return {
label: item.label,
value: item.value
};
}))
2) Your select should look like:
select: function (event, ui) {
$('#DistributorId').val(tempResults[ui.item.value]); // You are using item.key here
$('#DisplayDistributor').text(tempResults[ui.item.label]);
return false;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.