Reputation: 293
I am working in asp.net core. I am using typescript. I am using select2.
HTML:-
<select multiple="multiple" id="e1" class="js-example-basic-multiple js-states form-control js-data-example-ajax">
</select>
Script:-
$(".js-data-example-ajax").select2(
{
ajax: {
url: '/place',
dataType: 'json',
type: "GET",
data: function (term) {
return {
term: term
};
},
processResults: function (data) {
return {
results: data.items,
};
}
},
});
css and js:-
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
I take the values for select2 from the controller. When using this code, the values are returned from the controller. But not bind in the select2 dropdown.
I returned the Json data from the controller.
Can anyone suggest what mistake I have done?
Version of select2 : 4.0.3
Upvotes: 3
Views: 12533
Reputation: 109
You need to map result returned by api.
https://jsfiddle.net/vg7pgbcb/1/
$(".js-data-example-ajax").select2(
{
ajax: {
url: 'https://api.github.com/search/repositories',
dataType: 'json',
type: "GET",
delay: 250,
data: function (params) {
return {
q: params.term
};
},
processResults: function (data) {
var res = data.items.map(function (item) {
return {id: item.id, text: item.name};
});
return {
results: res
};
}
},
});
select2 expect id and text attribute to render the list
{
"results": [
{
"id": "CA",
"text": "California"
},
{
"id": "CO",
"text": "Colarado"
}
]
}
Upvotes: 10