Search code examples
jqueryjquery-select2jquery-select2-4

select2 results from server not displaying


I'm using Select2 4.0.3 trying to get the json returned from my server to appear as options in my drop down, but the results are simply not appearing when I open the drop down or search in the field.

<body>
    <select class="select2-student form-control">
    </select>
</body>

<script>
    $(document).ready(function () {
        $(".select2-student").select2({
            ajax: {
                url: "/MyUrl",
                data: function (params) {
                    return {
                        text: params.term
                    };
                },
                processResults: function (data, params) {
                    return {
                        results: data
                    };
                }
            }
        });
    });
</script>

I'm getting the response back as expected from the server when I enter matching text:

[{"Text":"My Student","Id":3}]

And I'm getting "No results found" in the drop down when I input a string that doesn't match the server-side criteria (i.e. doesn't match what's in the "text" field), but when results ARE returned there's not even a drop down appearing with anything in it - and I'm not getting any errors either in my browser.

I've tried a number of variations on this code all day and have yet to get anything to work. Advice?


Solution

  • Update for anyone that is having the same issue: I figured out what was going on here shortly after posting - the JSON coming back from the server wasn't camel case, so Select2 wasn't reading it correctly. Correct format should be:

    [{"text":"My Student","id":3}]
    

    So stupid to miss in retrospect, but it appears that ASP.NET doesn't format this way by default. I started using the JsonCamelCaseResult class from this question and that has been working perfectly.