Search code examples
javascriptajaxasp.net-mvcjquery-select2jquery-select2-4

How 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 display a simple dropdown from dynamic Data

The old way of version 3.6 doesn't work anymore:

I have a 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);   
 }

Thus, the data returned is:

[{"id":0,"text":"Smith"},{"id":1,"text":"John"},{"id":2,"text":"Philippe"}]

And I have a javascript code which worked on previous version 3.6:

$(".example-select2").select2({
        ajax: {
            dataType: 'json',
            url: '@Url.Action("GetSrcLanguages", "GetCheckSet")',
            results: function (data) {
                return {results: data};
            }              
        }
    });

It render an empty dropdownlist that displays 'No result found'

Do you know how to do it in v4.0?


Solution

  • Id is not the same as id, properties on JavaScript objects are case-sensitive. The same applies to Text and text as well, you want to use the 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 ajax.results method was renamed to ajax.processResults in 4.0.0 to avoid conflicting with AJAX transports that have an existing results method. So your JavaScript should actually look like

    $(".example-select2").select2({
        ajax: {
            dataType: 'json',
            url: '@Url.Action("GetSrcLanguages", "GetCheckSet")',
            processResults: function (data) {
                return {results: data};
            }              
        }
    });