Search code examples
jquery-select2large-datalargenumber

select2 + large number of records


I am using select2 dropdown. It's working fine for smaller number of items. But when the list is huge (more than 40000 items) it really slows down. It's slowest in IE.

Otherwise simple Dropdownlist works very fast, till 1000 records. Are there any workarounds for this situation?


Solution

  • ///////////////**** Jquery Code *******///////////////
    var CompanypageSize = 10;
    
    function initCompanies() {
            var defaultTxtOnInit = 'a';
            $("#DefaultCompanyId").select2({
                allowClear: true,
                ajax: {
                    url: "/SignUpTemplate/GetCompanies",
                    dataType: 'json',
                    delay: 250,
                    global: false,
                    data: function (params) {
                        params.page = params.page || 1;
                        return {
                            keyword: params.term ? params.term : defaultTxtOnInit,
                            pageSize: CompanypageSize,
                            page: params.page
                        };
                    },
                    processResults: function (data, params) {
                        params.page = params.page || 1;
                        return {
                            results: data.result,
                            pagination: {
                                more: (params.page * CompanypageSize) < data.Counts
                            }
                        };
                    },
                    cache: true
                },
                placeholder: {
                    id: '0', // the value of the option
                    text: '--Select Company--'
                },
                width: '100%',
                //minimumInputLength: 3,
            });
        }
    
    
    //////////******* Have to initialise in .ready *******///////////////
    
     $(document).ready(function () {
    
            initCompanies();
        });
    
    //////////******* C# code :: Controller is : SignUpTemplateController************/////
    
    public JsonResult GetCompanies(string keyword, int? pageSize, int? page)
        {
            int totalCount = 0;
            if (!string.IsNullOrWhiteSpace(keyword))
            {
                List<Companies> listCompanies = Companies.GetAll(this.CurrentTenant, (keyword ?? string.Empty).Trim(), false, 11, page.Value, pageSize.Value, ref totalCount, null, null, null, null, null).ToList();
                var list = listCompanies.Select(x => new { text = x.CompanyName, id = x.CompanyId }).ToList();
    
                return Json(new { result = list, Counts = totalCount }, JsonRequestBehavior.AllowGet);
            }
    
            return Json(null, JsonRequestBehavior.AllowGet);
        }