Reputation: 17
This my ajax for showing search item in select2
dropdown. But there is the problem. I am getting server response, but that response is not showing in select2
dropdown.
$('#txtTest').select2({
minimumInputLength: 2,
ajax: {
url: "/student/list/",
dataType: 'json',
type: "Get",
data: function(query) {
alert(query.term);
return { q: query.term };
},
processResults: function(data,page) {
console.log(data);
return {
results:data
}
}
}
});
Controller
public JsonResult list(string q)
{
var obj = (from c in db.selects
where c.name.ToLower().StartsWith(q.ToLower().Trim())
select new
{
Id=c.ID,
Text=c.name
}).ToList();
return Json(obj, JsonRequestBehavior.AllowGet);
}
In view my hidden text field
<input type="hidden" id="txtTest" class="input-xlarge" data-placeholder="Choose An Option.." />
Upvotes: 0
Views: 1339
Reputation: 21482
It looks like you are using Select2 v4. If that is the case, you need to change your hidden input element to a select element.
From the Select2 4.0.0 beta 1 release notes:
<select>
has replaced<input type="hidden" />
for all options (including remote data)
You could use:
<select id="txtTest" class="input-xlarge" data-placeholder="Choose An Option..">
</select>
Also, the objects you return should have id
and text
properties, whereas they currently have Id
and Text
properties. Either change the server code to return the correct property names, or change your processResults
function to correct the objects.
processResults: function(data) {
return {
results: $.map(data, function(item) {
return { id: item.Id, text: item.Text };
})
};
}
Upvotes: 2