How to display ajax data in select2.js v4.0?
I am using select2 v4.0 https://select2.github.io/ in an asp mvc project and I want to display a simple dropdown from dynamic data
The old version 3.6 way no longer works:
I have C # methode:
public JsonResult GetSrcMethod()
{
var list = new[]
{
new { id= 0, text= "Smith" },
new { id= 1, text= "John" },
new { id= 2, text= "Philippe" },
}.ToList();
Object json = JsonConvert.SerializeObject(list);
return Json(json, JsonRequestBehavior.AllowGet);
}
So the returned data is:
[{"id":0,"text":"Smith"},{"id":1,"text":"John"},{"id":2,"text":"Philippe"}]
And I have javascript code that worked on the previous 3.6 version:
$(".example-select2").select2({
ajax: {
dataType: 'json',
url: '@Url.Action("GetSrcLanguages", "GetCheckSet")',
results: function (data) {
return {results: data};
}
}
});
Displays an empty drop-down list that displays "No Result Found"
Do you know how to do this in version 4.0?
source to share
Id
is not the same as Id
, JavaScript object properties are case sensitive. The same goes for Text
and Text
, you want to use all lowercase versions.
public JsonResult GetSrcLanguages()
{
var list = new[]
{
new { id = 0, text = "Smith" },
new { id = 1, text = "John" },
new { id = 2, text = "Philippe" },
}.ToList();
Object json = JsonConvert.SerializeObject(list);
return Json(json, JsonRequestBehavior.AllowGet);
}
Also, the method ajax.results
was renamed in ajax.processResults
4.0.0 to avoid conflict with AJAX vehicles that have an existing method results
. Therefore, your JavaScript should look something like this:
$(".example-select2").select2({
ajax: {
dataType: 'json',
url: '@Url.Action("GetSrcLanguages", "GetCheckSet")',
processResults: function (data) {
return {results: data};
}
}
});
source to share