locked
Select 2 not populated with ajax RRS feed

  • Question

  • User799396372 posted

    hello

    i want populate the select 2 control with active directory users account, for inserting them to database, but even i see a json results in response by using F12 the select 2 is not populating

    the used select2 referenced in Shared/layout view

    there is by controller Action method

    public JsonResult GetUsersFiltredPaged(string match, int page = 1, int pageSize = 5)
            {
                PrincipalContext contextPrincipal = new PrincipalContext(ContextType.Domain);
                var userPrincipal = new UserPrincipal(contextPrincipal);
                PrincipalSearcher searchPrincipal = new PrincipalSearcher(userPrincipal);
                var totalCount = searchPrincipal.FindAll().Count();
                List<UserPrincipal> usersAD = new List<UserPrincipal>();
                
                foreach (UserPrincipal users in searchPrincipal.FindAll())
                {
                    if (users.EmployeeId != null)//prendre les comptes qui ayant un matricule paie
                    {
                        UserPrincipal userAd = users;
                        userAd.DisplayName = users.DisplayName + '(' + users.EmailAddress + ')';
                        userAd.EmployeeId = users.EmployeeId;
                        usersAD.Add(userAd);
                    }
                }
                IEnumerable<ModelDto> model = (from u in usersAD.AsQueryable().OrderBy(i=>i.DisplayName).Skip(page*(pageSize-1))
                                                    .Take(pageSize)
                                        select new ModelDto{id= u.EmployeeId, text=u.DisplayName});
                if (!string.IsNullOrWhiteSpace(match))
                {
                    model = model.Where(i => i.text.Contains(match));
                }
                     
                                        
                    ResultList<ModelDto> results = new ResultList<ModelDto> { items = model.ToList(), totalCount = usersAD.Count };
                    return Json(results, JsonRequestBehavior.AllowGet);
                
                
                
            }

    my drop down list razor

    @using (Html.BeginForm("RegisterModify", "Account", FormMethod.Post, new { @class = "form-horizontal"}))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
    
        <div class="well blanc" >
            
            <div class="form-group">
                @Html.LabelFor(model => model.SelectedMatric, new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownListFor(model => model.SelectedMatric, Model.DisplayedNames, "--Selectionnez--", new { @class = "form-control" })
                    @*@Html.HiddenFor(model => model.SelectedMatric, new { id="SelectedMatric"})*@
                    @Html.ValidationMessageFor(model => model.SelectedMatric, "", new { @class = "text-danger" })
                </div>
            </div>
    
    @*the rest of view *@
    <p>
                <input type="submit" value="Créer" class="btn btn-primary" />
    </p>

    the java script code

    $('#SelectedMatric').select2({
                    placeholder: "--Selectionnez--",
                    width: '100%',
                    minimumInputLength: 0,
                    allowClear: true,
                    ajax: {
                        url: '@Url.Action("GetUsersFiltredPaged")',
                        dataType: 'json',
                        type: 'Get',
                        
                        data: function (term, page) {
                            return { match: term, page: page, pageSize: 5 };
                        },
                        results: function (result, page) {
                            var more = (page * 5) < result.totalCount;
                            return { results: result.items, page: page, more: more };
                        }
                    }
                });

    Monday, October 14, 2019 9:41 AM

Answers

  • User-17257777 posted

    Hi Beginner32,

    I tested your codes and found the query parameters are incorrect. Besides, you should use “processResults” to receive the returned data, then populate the select2 control. I made a simple test:

    Model:

    public class ModelDto
        {
            public string id { get; set; }
            public string text { get; set; }
        }
    
        public class ResultList<T>
        {
            public List<T> items { get; set; }
            public int total_count { get; set; }
        }
    

    View:

    <select id="SelectedMatric" name="SelectedMatric"></select>
    <script>
    
            $(function () {
                $('#SelectedMatric').select2({
                    placeholder: "--Selectionnez--",
                    width: '50%',
                    minimumInputLength: 0,
                    allowClear: true,
                    ajax: {
                        url: '@Url.Action("GetUsersFiltredPaged")',
                        dataType: 'json',
                        type: 'Get',
                        
                        data: function (params) {
                            var query = {
                                match: params.term,
                                page: params.page || 1,
                                pageSize: params.pageSize || 5
                            }
                            return query;
                        },
                        processResults: function (data, params) {
                            console.log(params);
                            return {
                                results: data.items,
                                page:params.page,
                                pagination: {
                                    more:(params.page * 5) < data.total_count
                                }
                            }
                        },
                    },
                });
            })
    
        </script>
    

    Controller:

    public JsonResult GetUsersFiltredPaged(string match, int page = 1, int pageSize = 5)
            {
                List<ModelDto> model = new List<ModelDto>
                {
                    new ModelDto{id = "1", text  = "Option1" },
                    new ModelDto{id = "2", text  = "Option2" },
                    new ModelDto{id = "3", text  = "Option3" },
                    new ModelDto{id = "4", text  = "Option4" },
                    new ModelDto{id = "5", text  = "Option5" },
                };
    
                if (!string.IsNullOrWhiteSpace(match))
                {
                    model = model.Where(m => m.text.Contains(match)).ToList();
                }
    
                ResultList<ModelDto> results = new ResultList<ModelDto>
                {
                    items = model,
                    total_count = 5,
                };
                return Json(results, JsonRequestBehavior.AllowGet);
            }
    

    Result:

    Best Regards,

    Jiadong Meng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, October 15, 2019 10:03 AM

All replies

  • User-17257777 posted

    Hi Beginner32,

    I tested your codes and found the query parameters are incorrect. Besides, you should use “processResults” to receive the returned data, then populate the select2 control. I made a simple test:

    Model:

    public class ModelDto
        {
            public string id { get; set; }
            public string text { get; set; }
        }
    
        public class ResultList<T>
        {
            public List<T> items { get; set; }
            public int total_count { get; set; }
        }
    

    View:

    <select id="SelectedMatric" name="SelectedMatric"></select>
    <script>
    
            $(function () {
                $('#SelectedMatric').select2({
                    placeholder: "--Selectionnez--",
                    width: '50%',
                    minimumInputLength: 0,
                    allowClear: true,
                    ajax: {
                        url: '@Url.Action("GetUsersFiltredPaged")',
                        dataType: 'json',
                        type: 'Get',
                        
                        data: function (params) {
                            var query = {
                                match: params.term,
                                page: params.page || 1,
                                pageSize: params.pageSize || 5
                            }
                            return query;
                        },
                        processResults: function (data, params) {
                            console.log(params);
                            return {
                                results: data.items,
                                page:params.page,
                                pagination: {
                                    more:(params.page * 5) < data.total_count
                                }
                            }
                        },
                    },
                });
            })
    
        </script>
    

    Controller:

    public JsonResult GetUsersFiltredPaged(string match, int page = 1, int pageSize = 5)
            {
                List<ModelDto> model = new List<ModelDto>
                {
                    new ModelDto{id = "1", text  = "Option1" },
                    new ModelDto{id = "2", text  = "Option2" },
                    new ModelDto{id = "3", text  = "Option3" },
                    new ModelDto{id = "4", text  = "Option4" },
                    new ModelDto{id = "5", text  = "Option5" },
                };
    
                if (!string.IsNullOrWhiteSpace(match))
                {
                    model = model.Where(m => m.text.Contains(match)).ToList();
                }
    
                ResultList<ModelDto> results = new ResultList<ModelDto>
                {
                    items = model,
                    total_count = 5,
                };
                return Json(results, JsonRequestBehavior.AllowGet);
            }
    

    Result:

    Best Regards,

    Jiadong Meng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, October 15, 2019 10:03 AM
  • User799396372 posted

    thank you but what if total_counts > 5

    Wednesday, October 16, 2019 8:21 AM