3

I have a view where I am trying to implement the auto populate the text box/drop down field. I am using a list which I query on.

I am following this example http://www.dotnetqueries.com/Article/159/how-to-implement-select2-with-ajax-and-json-in-asp-net-mvc , break point does not even hit the method in my controller. so is there something wrong with the way I set this up or the way the action result method is called in controller.

using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using TestSelect2.Models;
using Controller = Microsoft.AspNetCore.Mvc.Controller;
    
    namespace TestSelect2.Controllers
    {
        public class HomeController : Controller
        {
            private readonly ILogger<HomeController> _logger;
    
            public HomeController(ILogger<HomeController> logger)
            {
                _logger = logger;
            }
    
            public IActionResult Index()
            {
                return View();
            }
    
          
            [Microsoft.AspNetCore.Mvc.HttpPost]
            [Microsoft.AspNetCore.Mvc.Route("/home/account-list")]
            public Microsoft.AspNetCore.Mvc.ActionResult GetAccounts(string q)
            {
                List<Account> accounts = new List<Account>();
                // Add parts to the list.
                accounts.Add(new Account() { Id = 1, AccountNumber = "MVP1" });
                accounts.Add(new Account() { Id = 1, AccountNumber = "MVP11" });
                accounts.Add(new Account() { Id = 1, AccountNumber = "ABC2" });
                accounts.Add(new Account() { Id = 1, AccountNumber = "ABC3" });
                accounts.Add(new Account() { Id = 1, AccountNumber = "XYZ3" });
                accounts.Add(new Account() { Id = 1, AccountNumber = "XYZ4" });
    
     
                        
                    if (!(string.IsNullOrEmpty(q) || string.IsNullOrWhiteSpace(q)))
                    {
                        accounts = accounts.Where(x => x.AccountNumber.ToLower().StartsWith(q.ToLower())).ToList();
                    }
                    return Json(new { items = accounts }, JsonRequestBehavior.AllowGet);
            }
          
    
        }
    }



    @{
        Layout = null;
    }
    <!DOCTYPE html>
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Select2 DEMO</title>
        <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 () {
                $(".accountSelect").select2({
                    ajax: {
                        url: '/home/account-list',
                        width: 'resolve',
                        data: function (params) {
                            return {
                                q: params.term// search term
                            };
                        },
                        processResults: function (data) {
                            return {
                                results: data.items
                            };
                        },
                        minimumInputLength: 2,
                        width: 'resolve'
                    }
                });
     
            });
        </script>
        <style>
            body {
                margin: auto;
                width: 600px;
                padding: 50px;
            }
    
            .accountSelect {
                width: 400px;
            }
        </style>
    </head>
    <body>
    <form method="post">
    
        <select class="accountSelect"></select>
    </form>
    </body>
    </html>

2 Answers 2

3

Remove the [HttpPost] attribute on GetAccounts action. Since the ajax makes a get request.And the tutorial you follow is for asp.net but not asp.net core, there is no JsonRequestBehavior.

Note: select2model must with id and text two properties, otherwise, it can't be recognized. Change your Account model like below:

public class Account
{
    public int Id { get; set; }
    public string Text { get; set; }
}

And the controller action, make sure the id can't be the same.

[Route("/home/account-list")]
public IActionResult GetAccounts(string q)
{
    List<Account> accounts = new List<Account>();
    // Add parts to the list.
    accounts.Add(new Account() { Id = 1, Text = "MVP1" });
    accounts.Add(new Account() { Id = 2, Text = "MVP11" });
    accounts.Add(new Account() { Id = 3, Text = "ABC2" });
    accounts.Add(new Account() { Id = 4, Text = "ABC3" });
    accounts.Add(new Account() { Id = 5, Text = "XYZ3" });
    accounts.Add(new Account() { Id = 6, Text = "XYZ4" });


    if (!(string.IsNullOrEmpty(q) || string.IsNullOrWhiteSpace(q)))
    {
        accounts = accounts.Where(x => x.Text.ToLower().StartsWith(q.ToLower())).ToList();
    }
    return Json(new { items = accounts });
}

View and Scripts:

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Select2 DEMO</title>
    <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 () {
            $(".accountSelect").select2({
                minimumInputLength: 2,
                ajax: {
                    url: '/home/account-list',
                    data: function (params) {
                        return {
                            q: params.term// search term
                        };
                    },
                    processResults: function (data) {
                        return {
                            results: data.items
                        }
                    },
                }
            });
        });
    </script>

    <style>
        body {
            margin: auto;
            width: 600px;
            padding: 50px;
        }

        .accountSelect {
            width: 400px;
        }
    </style>
</head>
<body>
    <form method="post">
        <select class="accountSelect"></select>
    </form>

</body>
</html>

Result:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

1

You may try as below:

//1. Action Method Which Returns the data. 
public ActionResult GetSelect2Data(string query)
{
    //In Realtime This should come from the Database
    List<DropDownItem> collection = new List<DropDownItem>() {
        new DropDownItem(){ Value = 1,  Text = "Switzerland"},
        new DropDownItem(){ Value = 2,  Text = "Canada"},
        new DropDownItem(){ Value = 3,  Text = "Japan"},
        new DropDownItem(){ Value = 4,  Text = "Germany"},
        new DropDownItem(){ Value = 5,  Text = "Australia"},
        new DropDownItem(){ Value = 6,  Text = "United Kingdom"},
        new DropDownItem(){ Value = 7,  Text = "United States"},
        new DropDownItem(){ Value = 8,  Text = "Sweden"},
        new DropDownItem(){ Value = 9,  Text = "India"},
       new DropDownItem(){ Value = 10,  Text = "Russia"},
     };


        var searchResult = from c in collection
                           where c.Text.Contains(query, 
   StringComparison.CurrentCultureIgnoreCase)
                           select c;

        return Json(searchResult.ToList());
    }



///2. JS Method which binds any HTML Select as Select2 or Smart Select.   
///In the User Interface (.cshtml file)You may define a framework JS Function as  which could be used anywhere
function registerSelect2(dropDownSelector, ajaxUrl) {
$(dropDownSelector).select2({
    ajax: {
    url: ajaxUrl,
    dataType: 'json',
    delay: 10,
    type: 'GET',
    data: function (params) {
    return {
        query: params.term, // search term
    };
    }
    , processResults: function (data) {
    return {
    results: $.map(data, function (item) {
        return {
            id: item.value,
            text: item.text,
        };
    })
    };
    },
    cache: true,
},
    minimumInputLength: 3,
    allowHtml: true,
    allowClear: true
});
}


//3. Invoke the JS Function to make any particular Select a Select2. 
$(function () {
    //Just you need to pass the Selector of your control and the Ajax Url from which data has to be loaded
    registerSelect2("#ddlSelect2", "/user/GetSelect2Data");
});


//This is the Simple Select which's made a Select2 Control. Paste it somewhere in the UI
<select id="ddlSelect2"></select>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.