locked
How to populate Json data in a Select2 jQuery RRS feed

  • Question

  • User1242168447 posted

    I'm trying to display data into a Select2 thru jQuery but no success.

    I searched and found many (almost) similar solutions but they don't apply to my issue.

    Indeed, I'm able to display the Json string in the correct format when I navigate directly to the URL

    https://localhost:44190/Finance/Financial/GetUsersList

    but pulling the data into a Select button in Index page that's the challenge.

    In brief I want to populate the jquery select2 with data from GetUsersList() method.

    Besides, I was also trying as second solution I thought about which is to pass data from ViewData in the controller to Index page inside Select tag that's why there's ViewData in the below controller but I also still can't achieve it.

    Can you please assist ? 

    public class User
        {
    
            public Guid Id { get; set; }
    
            public string Name { get; set; }
    
            public string Department { get; set; }
    
            public string photo { get; set; }
        }
        
    
        public virtual DbSet<User> User { get; set; }
    
        
        public class Select2UserViewModel
        {
            public Guid Id { get; set; }
            public string Users { set; get; }
    
        }
    
        
        
        public IActionResult GetUsersList()
        {
                
            var selectedData = _context.User.Select(x => new
            {
                id = x.Id,
                name = x.Name
            });
    
            ViewData["userList"] =  selectedData;
            
            return Json(selectedData);
        }
    

    The remaining code

    <script>
        
        $(document).ready(function () {
        
            $("#LoadUsers").select2({
                        allowClear: true,
                        blurOnChange: true,
                        openOnEnter: false,
                        ajax: {
                            url: "/Finance/Financial/GetUsersList",
                            dataType: 'json',
                            data: function (term, page) {
                                return {
                                    name: term
                                };
                            },
                            results: function (data, page) {
                                return { results: data };
                            }
                        },
                        error: function () {
                            alert('Failed');
                        },
                        formatResult: function (data) {
                            return "<div class='select2-user-result'>" + data.client + "</div>";
                        },
                        formatSelection: function (data) {
                            return data.client;
                        }
            });
        });
        
         </script>
    Wednesday, September 30, 2020 6:05 PM

Answers

  • User711641945 posted

    Hi LetMeCode,

    In asp.net core,select2model must with id and text two properties, otherwise, it can't be recognized.

    Change your code like below:

    <select id="LoadUsers" style="width:400px;"></select>
    @section Scripts
    {
        <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
    
        <script>
            $(document).ready(function () {
                $("#LoadUsers").select2({
                    allowClear: true,
                    blurOnChange: true,
                    openOnEnter: false,
                    ajax: {
                        url: "/Home/GetUsersList",
                        dataType: 'json',
                        data: function (params) {
                            return {
                                name: params.term
                            };
                        },
                        processResults: function (data, page) {
                            return { results: data };
                        }
                    },
                    error: function () {
                        alert('Failed');
                    },
                    formatResult: function (data) {
                        return "<div class='select2-user-result'>" + data.client + "</div>";
                    },
                    formatSelection: function (data) {
                        return data.client;
                    }
                });
            });
        </script>
    

    Controller:

    public IActionResult GetUsersList(string name)
    {
    
        var selectedData = user.Select(x => new
        {
            id = x.Id,
            text = x.Name
        });
    //if you need to make search item work,add the following code if (!(string.IsNullOrEmpty(name) || string.IsNullOrWhiteSpace(name))) { selectedData = selectedData.Where(x => x.text.ToLower().StartsWith(name.ToLower())).ToList(); } return Json(selectedData); }

    Result:

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 1, 2020 7:05 AM

All replies

  • User-474980206 posted

    what does the javascript debugger show for the response. also it looks like your using an old version of select2 that supported formatResult & formatSelection, which have coding errors in your sample. there is no data.client defined in the response.

    you should probably upgrade to the current version, and following the documentation.

      https://select2.org

    Wednesday, September 30, 2020 6:31 PM
  • User1242168447 posted

    Thanks Bruce for trying to help.

    I'm actually using the latest stable version of select2 which is version  4.0.13

    Wednesday, September 30, 2020 11:51 PM
  • User-474980206 posted

    then if you read the docs there is no formatResult or formatSelection options in the current version. also you could just format on server, so the client did not need to:

    public IActionResult GetUsersList()
    {
            return return Json(new 
            {
                results = _context.User.Select(x => new
                {
                    id = x.Id,
                    name = x.Name
                }).ToList();
            });
    }
    

    Thursday, October 1, 2020 2:56 AM
  • User711641945 posted

    Hi LetMeCode,

    In asp.net core,select2model must with id and text two properties, otherwise, it can't be recognized.

    Change your code like below:

    <select id="LoadUsers" style="width:400px;"></select>
    @section Scripts
    {
        <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
    
        <script>
            $(document).ready(function () {
                $("#LoadUsers").select2({
                    allowClear: true,
                    blurOnChange: true,
                    openOnEnter: false,
                    ajax: {
                        url: "/Home/GetUsersList",
                        dataType: 'json',
                        data: function (params) {
                            return {
                                name: params.term
                            };
                        },
                        processResults: function (data, page) {
                            return { results: data };
                        }
                    },
                    error: function () {
                        alert('Failed');
                    },
                    formatResult: function (data) {
                        return "<div class='select2-user-result'>" + data.client + "</div>";
                    },
                    formatSelection: function (data) {
                        return data.client;
                    }
                });
            });
        </script>
    

    Controller:

    public IActionResult GetUsersList(string name)
    {
    
        var selectedData = user.Select(x => new
        {
            id = x.Id,
            text = x.Name
        });
    //if you need to make search item work,add the following code if (!(string.IsNullOrEmpty(name) || string.IsNullOrWhiteSpace(name))) { selectedData = selectedData.Where(x => x.text.ToLower().StartsWith(name.ToLower())).ToList(); } return Json(selectedData); }

    Result:

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 1, 2020 7:05 AM
  • User1242168447 posted

    Hi rena, thank you so much for your help.

    Your code worked for me nicely. You saved me many hours. Thank you so much !

    But I was getting an error due to cast in line below, I fixed that error in adding (dynamic) as shown below or in removing ToList() at the end.

    but the overall code worked like shame.

    selectedData = selectedData.Where(x => x.text.ToLower().StartsWith(name.ToLower())).ToList();
    


    Error    CS0266    Cannot implicitly convert type 'System.Collections.Generic.List<<anonymous type: System.Guid id, string text>>' to 'System.Linq.IQueryable<<anonymous type: System.Guid id, string text>>'. An explicit conversion exists (are you missing a cast?)  

    --

    Fix 

    selectedData = (dynamic)selectedData.Where(x => x.text.ToLower().StartsWith(name.ToLower())).ToList();
    
    selectedData = selectedData.Where(x => x.text.ToLower().StartsWith(name.ToLower()));
    
    Thursday, October 1, 2020 10:31 AM
  • User1242168447 posted

    Can you please advise me on how to learn advanced concept of asp.net core?

    cause I've been reading ebooks (so far 2 books) but I still can't do this small things, which I wasted hours.

    Do I need to practice more instead of reading ebooks ?

    Thursday, October 1, 2020 10:32 AM
  • User1242168447 posted

    By the way, how do I make the select tag (dropdown List) to be fixed, with no search. ?

    Thursday, October 1, 2020 10:50 AM
  • User711641945 posted

    Hi LetMeCode,

    Can you please advise me on how to learn advanced concept of asp.net core?

    You could refer to the official document by following the left menu with `Advanced` tab:

    https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.1

     how do I make the select tag (dropdown List) to be fixed, with no search. ?

    <script>
        $(document).ready(function () {
            $("#LoadUsers").select2({
                allowClear: true,
                blurOnChange: true,
                openOnEnter: false,
                minimumResultsForSearch: -1,
                ajax: {
                    url: "/Home/GetUsersList",
                    dataType: 'json',
                    //data: function (params) {
                    //    return {
                    //        name: params.term
                    //    };
                    //},
                    processResults: function (data, page) {
                        return { results: data };
                    }
                },
            });
        });
    </script>

    Best Regards,

    Rema

    Friday, October 2, 2020 6:10 AM