0

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?

jbindert
  • 11
  • 1
  • 5

2 Answers2

3

I know this is quite an old question, but a nicer way to do it would be to do something like this:

            processResults: function(data) {
                return {
                    results: jQuery.map(data, function(item) {
                        return {
                            id: item.key,
                            text: item.value
                        }
                    })
                };
            },

That way you can just return a standard collection of mapped objects, without worrying about any casing.

Jon Betts
  • 234
  • 3
  • 16
1

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.

Community
  • 1
  • 1
jbindert
  • 11
  • 1
  • 5