Automatically populate select2 dropdown in ASP.NET MVC Core using AJAX

Currently, I am working on a feature to automatically populate text boxes and drop-down fields in my view. To achieve this, I am using a list that I query again.

I came across an example that I am referencing here. However, when trying to debug, the break point is not hitting the method in my controller. I am unsure if there is an issue with how I set everything up or perhaps how the action result method is called in the 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>

Answer №1

To ensure the functionality of your GetAccounts action with AJAX, it is recommended to remove the [HttpPost] attribute as the request method should be GET. Additionally, please note that if you are following a tutorial for asp.net and not asp.net core, there is no need for JsonRequestBehavior.

It is essential for the select2model to have both the id and text properties in order to be properly recognized. Update your Account model as shown below:

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

Furthermore, ensure that the IDs in the controller action are unique. See the updated code snippet below:

[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 });
}

For the view and scripts, make sure to include the necessary dependencies and create the script to initialize the select2 plugin. Here's an example setup:

@{
    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>

Finally, don't forget to check the result of your implementation.

https://i.stack.imgur.com/wpzNs.gif

Answer №2

Here is a possible solution:

//1. Creating an action method to retrieve data from the database.
public ActionResult GetSelect2Data(string query)
{
    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. Defining a JavaScript method for binding HTML Select as Select2 or Smart Select.  
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. Invoking the JS Function to convert a particular Select element into a Select2 dropdown. 
$(function () {
    registerSelect2("#ddlSelect2", "/user/GetSelect2Data");
});

//This is the Simple Select which has been transformed into a Select2 Control. Add this code in the UI
<select id="ddlSelect2"></select>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the optimal method for sending an error response to an Ajax request?

After I call a WebMethod using ajax and return a simple string, the success method of the ajax code is executed without any errors. Here's an example: [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public static string Hello() { ...

Tap to reveal additional information with the power of Jquery and ajax

I have a question regarding the popup slide functionality. I would like to achieve the following: Currently, I am using the following code to display post details upon clicking: function getPostDetails(id){ var infoBox = document.getElementById("in ...

Using JSON data that has been returned to populate a table - Tablednd

I am enhancing a wishlist plugin to allow the user to rearrange the table by dragging and dropping items. Currently, I have implemented jQuery Tablednd with the return of JSON data after making an ajax call. The functionality is working fine. However, I a ...

Exploring the World of Infinite Scrolling with React.js and Material_ui

I am currently working on a project using react.js As part of this project, I need to implement a board with infinite scroll similar to Facebook I have a specific question regarding this implementation. When scrolling the board and loading more posts li ...

Determining the appropriate version of the types package for your needs

It has come to my attention that certain npm packages do not come with types included. Because of this, the community often creates @types/packagename to provide those types. Given that both are packages, how does one determine which version of the types ...

How can I create a redirect link in HTML that opens in a new window

I have a HTML page where I need to redirect to the next page. <a href="www.facebook.com" target="_blank">www.facebbok.com</a> Currently, it is redirecting to localhost:9000/dashboard/www.facebook.com But I only want to redirect to www.facebo ...

Using VueLoaderPlugin() results in an 'undefined error for 'findIndex' function

Currently, I am in the process of integrating a Vue CLI app into another web project that we are actively developing. The Vue app functions without any issues when utilizing the development server bundled with Vue CLI. Due to the presence of .vue files wi ...

Ways to transmit data to database without having to refresh the page

Struggling with sending data to the database using AJAX? The submit button doesn't seem to trigger any action and the page remains static. All JavaScript files are correctly referenced, so it's puzzling why things aren't working as expected. ...

Selenium - How to pass a file path to a dynamically generated input element that is not visible in the DOM

Check out this example of HTML code: This is how you create a visible button and display the selected file: <button id="visible-btn">visible button</button> <p>selected file is: <span id="selected-file"></spa ...

Problem with Bootstrap multiselect: it only opens the first time, and stops working after an ajax call

I am having trouble using Bootstrap multiselect with jQuery ajax. When I run the ajax code, the multiselect button stops working properly. To see the issue in action, click here: and look at the last multiselect dropdown. Here is the ajax code snippet: ...

Changes to the state will not be reflected until a poll is conducted

Here we have an example of state being initialized and passed down to a child component: const [rowCount, setRowCount] = React.useState<number>(1); <Foo setRowCount={setRowCount} /> Foo: const Foo = (props) => { const { setRowCount } ...

Concealing/Revealing Elements with jquery

For hours, I've been attempting to switch between hiding one element and showing another in my script. Here is the code I am using: <script type="text/javascript"> function () { $('#Instructions').hide(); $('#G ...

Is it feasible to implement different themes besides 'light' and 'dark' in React Material UI?

Currently, I am developing a user interface (UI) using React in combination with Material UI (v5+). The documentation provides information on how to utilize the extendTheme function along with CssVarsProvider to incorporate MUI colors into CSS. It also men ...

Is the accuracy of the in-situ convolution filter guaranteed?

After analyzing my simple box blur function, I have come to the realization that it may be incorrect. The current implementation edits the ImageData object in place, leading to convolution filters depending on surrounding pixels that have already been ch ...

Seeking assistance to transfer div elements into a different div post an onclick event

I have a container that contains four separate divs. My goal is to append the remaining three divs to another specific div after clicking on one of them. Does anyone know how I can achieve this? <!DOCTYPE html> <html lang="en"> < ...

"Although disabled, input elements can still be focused on in Firefox browser

Illustrative example let userInput = document.createElement("input"); userInput.id = "user-input"; userInput.type = "number"; userInput.className = "user-number-input"; userInput.disabled = true; document.body.appendChild(userInput); .number-inp ...

Is there a way to retrieve all active HTTP connections on my Express.js server?

In my express server app, I am implementing SSE (server send events) to inform clients about certain events. Below is the code snippet from my server: sseRouter.get("/stream", (req, res) => { sse.init(req, res); }); let streamCount = 0; class SS ...

The Socket IO Client is receiving a different object than the one that was sent by the Server

My server side code is sending an object to the client side, but the object received by the client is completely different from what was sent. Let me elaborate: Code Server side code: //Setting up the example var response={}; response.models=[]; respo ...

Slider with FadeIn effect remains unresponsive to the FadeOut command (JQuery / Javascript)

I'm currently working on a slider that is supposed to fade in and out. However, I am facing an issue where the slide fades in correctly but instantly disappears instead of fading out. Do you have any insights into why this might be happening and any s ...

Implementing CSS keyframes when a specified PHP condition is satisfied

I am looking to implement an opening animation on my website that should only play when a user visits the site for the first time. I want to avoid displaying the animation every time the page is reloaded, so it should only run if a cookie indicating the us ...