0

I am trying to populate data into Select2 dropdown using JSON which is returned by a controller class.But it is not working.There is no error.Here is the code

client Side

$("#products").select2({
        minimumInputLength: 2,
        ajax: {
            url: "Search",
            dataType: 'json',
            type: "POST",
            quietMillis: 50,
            data: function (term) {
                return {
                    "q": JSON.stringify(term),
                };
            },
            results: function (data) {
                return {
                    results: $.map(data, function (item) {
                        return {
                            text: item.text,
                            id: item.id
                        }
                    })
                };
            }
        }
    });

Controller Action

 [HttpPost]
    public JsonResult Search(string q)
    {
       //testing data
       return Json(new products() {id = "2", text = "biotouch"});      
    }

Product class

public class products()
{
  public string id{get;set;}
  public string text{get;set;}
}

2 Answers 2

1

It worked when I changed

 results: function (data) {

to

ProcessResults: function (data) {
Sign up to request clarification or add additional context in comments.

Comments

0
$("#products").select2({
            minimumInputLength: 2,
            ajax: {
                url: "YourControllerName/Search",
                dataType: 'json',
                type: "POST",
                quietMillis: 50,
                data: function (term) {
                    return {
                        "q": JSON.stringify(term),
                    };
                },
                results: function (data) {
                    return {
                        results: $.map(data, function (item) {
                            return {
                                text: item.text,
                                id: item.id
                            }
                        })
                    };
                }
            }
        });

I have added controller name in URL you forgot to add controller name in url.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.