Error with slice select2.js

0

I'm having trouble filling out a combobox with Select2

I have my JS:

$("#comboplatos").select2({
    placeholder: "Type to select a sponsor",
    minimumInputLength: 3,
    allowClear: true,
    style: "display: inline-block",
    width: 400,
    ajax: {
        cache: false,                      
        dataType: 'json',
        type: "GET",
        url: "/Admin/LlenarDestinoconJSON",
        data: function (params) {
            return {
                query: params.term,
                page: params.page// search term
            };

        },
        results: function (data) {
            return { results: data };
        }
    },
    formatResult: contractFormatResult,
    formatSelection: contractFormatSelection,
    escapeMarkup: function (m) { return m; }        
});

And my controller is:

public JsonResult LlenarDestinoconJSON(string query)
    {
        var lista = CMM_PersonaNeg.Instancia.Listar(query);
        var JSonLista = Json(lista.ToList(), JsonRequestBehavior.AllowGet);
        return JSonLista;
    }

When executing the application, through the debug I can get the data I want, but it does not show me anything in the combo and this error appears in console:

  

select2.js: 4008 Uncaught TypeError: Can not read property 'slice' of undefined

I have no idea how to solve it, look in several forums but I did not find any solution that could help me.

I hope you can tell me if something is wrong with my code or if something is missing.

Thank you very much.

    
asked by Jesus 19.06.2017 в 08:07
source

1 answer

0

The problem may be in how you receive the json or the structure of json

If the json you receive does not contain at least one identifier id and text will not show anything, I suggest you modify your json from results

ajax: {
    ...,
    //si con results no funciona probar con processResults
    //processResults: function (data, params) {
    results: function (data, params) {
        //recorriendo el json pare crear uno con la informacion esperada
        data.results = data.map(function (obj) {
          return {
            "text": obj.Nombre,
            "id": obj.id
          };
        });
        //retornando los valores esperados en el formato esperado por el plugin
        return { results: data.results };
    }
},

This change is necessary because the json expected by the plugin contains at least the following:

{
  results: [
    {id:1, text:"Hola Mundo"},//Puede llevar otros parámetros pero no los reconocerá 
    {id:2, text:"Probando Json"}
  ]
}
    
answered by 19.06.2017 в 16:24