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

Cannot get selected value of Select2 dropdownlist


I use Select2 Dropdown dropdownlist in my MVC project as shown below. Although I can pass the "query" parameter via AJAX by setting it directly, I cannot get the selected text or value of dropdownlist in the data section below. How to get it?

@Html.DropDownListFor(x => x.StudentId, Enumerable.Empty<SelectListItem>(), 
    new { style ="width: 100%;" } )

$("#StudentId").select2({
   multiple: false,
   placeholder: "Select",
   allowClear: true,
   tags: true,

   ajax: {
       url: '/Grade/StudentLookup',
       dataType: 'json',
       delay: 250,

       data: function (params) {
           return {
               //q: params.Name, // search term
               //page: params.page
               query : 'test' //this parameter can be passed via AJAX
               //!!! but I cannot get the selected text or value of dropdownlist 
           };
       },              

       processResults: function (data, page) {
           var newData = [];
           $.each(data, function (index, item) {
               newData.push({
                   id: item.Id,     //id part present in data 
                   text: item.Name  //string to be displayed
               });
           });
           return { results: newData };
       },
       cache: true
   },
   escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
   minimumInputLength: 0, //for listing all, set : 0
   maximumInputLength: 20, // only allow terms up to 20 characters long
});

Solution

  • ============================== S O L V E D ==============================

    Here is the solution of the problem:

    In order to send the text value in Select2 via AJAX use params.term in the data section as shown below. Many thanks to @DavidDomain as his answer also very useful in order to use selected index change.

    //code omitted for brevity
    data: function (params) {
       return {
                 query: params.term, // search term
                 page: params.page
               };
       }, 
    ...