简体   繁体   中英

Select2 - Can't select a value?

Release version (Select 4.0.1)

HTML

<select id="search_customers" style="width: 300px;"></select>

Javascript:

$("#search_customers").select2({
  multiple: false,
  allowClear: true,
  ajax: {
    url: "@Url.Action("
    SearchCustomers ", "
    Home ")",
    dataType: 'json',
    delay: 250,
    data: function(params) {
      return {
        id: params.term, // search term
      };
    },
    processResults: function(data, params) {
      return {
        results: data
      } // Data is a List<T> of id an text
    },
  }
});

The dropdown works, and I can see my records, however, when I click on one of the options the box closes, and the selected record isn't shown. My box looks like this

捕获

I've tried everything I can think of. The issue appears in all browsers. The data being return is a list of id/text pairs.

Controller code

var customers = this.service.SearchCustomers(id).Select(x => new { id = x.CustomerID, text = x.CustomerName }).ToList();

return Json(customers, JsonRequestBehavior.AllowGet);

My customer ID's had leading spaces for some reason. (Old ERP system), so adding a .Trim() call to the select statement on the customer ID fixed it. Apparently select2 doesn't like " 56", but "56" is fine!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM