Select2的远程数据操作

 一、概述

    如果下拉列表框中的内容太多,最好是使用Select2的远程数据进行筛选。

二、参考文献

https://select2.github.io/examples.html#data-ajax

https://github.com/select2/select2/issues/2950

三、前端Ajax配置

$(elemStr).select2(
            {
                placeholder: 'Enter name',
                //Does the user have to enter any data before sending the ajax request
                minimumInputLength: 1,
                allowClear: true,
                language: "zh-CN",
                ajax: {
                    //How long the user has to pause their typing before sending the next request
                    delay: 250,
                    //The url of the json service
                    url: "/Controller/Action",
                    dataType: 'json',
                    //Our search term and what page we are on
                    data: function (params) {
                        if (params.term == "undefined") {
                            searchItem = " ";
                        }
                        else {
                            searchItem = params.term;
                        }
                        var query = {
                            searchTerm: searchItem,
                            pageSize: 20,
                            pageNum: params.page || 1

                        };                       
                        return query;
                    },
                    processResults: function (data, params) {
                        //Used to determine whether or not there are more results available,
                        //and if requests for more data should be sent in the infinite scrolling
                        params.page = params.page || 1;                        return {
                            results: data.results,
                            pagination: {
                                more: (params.page * 20) < data.total
                            }
                        };
                    },
                    cache: true
                }
            });

具体的参数说明见参考文献的指南,说几个重点参数:

1. 自定义向后台传输参数:

data: function (params) {
                       
                        var query = {
                            searchTerm: searchItem,
                            pageSize: 20,
                            pageNum: params.page || 1

                        };                       
                        return query;
                    },

向后台传输了输入框中的值:searchTerm, 整个下拉列表中可显示的数量:pageSize,当前页码:pageNum

2. 结果返回后的处理过程:

return {
         results: data.results,
         pagination: {
         more: (params.page * 20) < data.total
        }       

data.results与data.total是后台传送回来的json格式,此处需注意results与total必须是小写!(见参考文献2)

 四、后端处理

1. 符合select2格式的模型

 public class Select2Result
    {
        public string id { get; set; }
        public string text { get; set; }
    }

2. 返回到select2回调函数的模型

 public class Select2PagedResult
    {
        public int total { get; set; }
        public List<Select2Result> results { get; set; }
    }

3. Controller/Action

[HttpGet]
        public async Task<IActionResult> GetDepartmentPersonSelectList(string searchTerm = null, int pageSize = 20, int pageNum = 1)
        {
            
            var departmentPersonListQuery = repo.GetAll();

            if (!String.IsNullOrEmpty(searchTerm))
            {
                departmentPersonListQuery = departmentPersonListQuery.Where(a => a.SpellingFirstCode.Contains(searchTerm));
            }
            var total = await departmentPersonListQuery.CountAsync();

            var departmentPersonList = await departmentPersonListQuery.OrderBy(a => a.SpellingFirstCode)
                .Skip(pageSize * (pageNum - 1))
                .Take(pageSize).Select(a => new Select2Result { id = a.PersonID.ToString(), text = a.PersonName })
                .ToListAsync();
            Select2PagedResult result = new Select2PagedResult { total = total, results = departmentPersonList };

            return new JsonResult(result);
        }
原文地址:https://www.cnblogs.com/hahaxi/p/7323719.html