How to implement select2 with ajax and json in asp.net mvc



In this article we will learn how to load data in select2 jquery dropdown from database using ajax and json .select2 has various built in features to use ajax and json . whenever the user puts the cursor in the dropdown the ajax call triggers and loads the data in the dropdown.

Follow the below steps in order implement select2 with ajax.

Project Creation:

  1. Open Visual Studio. Select “New”  a Project from the File Menu.

  2. In the New Project window, expand C#, click Web, and then click the ASP.NET MVC 4 Web Application project template.

  3. Give the project and solution name as ”SampleApplication”, and then click OK.

  4. In the New ASP.Net MVC4 Project Window, select the Basic template. Ensure that the selected view engine is Razor .Click the OK button to crate the project.

Home Controller Creation:

Steps to create new controller

  1. Right click on the controller folder

  2. Select “Add”

  3. Select “Controller” option

  4. “Add Controller” dialog window ,name the controller “HomeController”

  5. Click the Add button.

  6. When you are done , the controller should look like this.

Controller Code

public class HomeController : Controller
 {
    public ActionResult  Index()
    {
       return View();
    }
 }

View Creation:

  1. Go to HomeController

  2. Right click on the “Index()” action.

  3. Click “Add”

  4. Select “View”.

  5. An “Add View window” will be opened,

  6. Give the view name  as “Index”

  7. Click the “Add” button.

     8.  Include the following css and js files in <head> section .

  <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
  <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

9.when you are done the “view” should look like this.

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Select2 with Ajax</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
</head>
<body>
    <div class="container">
        <div class="form-group">
            <label for="Select Country">Select Country</label>
            <select multiple="multiple" class="chose-country form-control"></select>
        </div>
    </div>
    <script>
        $(document).ready(function () {
            $(".chose-country").select2({
                ajax: {
                    url: '/Home/GetEmployeeList',
                    width: 'resolve',
                    data: function (params) {
                        return {
                            q: params.term// search term
                        };
                    },
                    processResults: function (data) {
                        return {
                            results: data.items
                        };
                    },
                    minimumInputLength: 2,
                    width: 'resolve'
                }
            });
 
        });
    </script>
</body>
</html>

10.Create a Class file with the following properties under Models Folder .

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

Note : we must use the same property names like above because select2 jquery plugin will accept only these property names.

11.Create another action in HomeController which will be called whenever the user puts the cursor in the dropdown i.e when the cursor is placed in this dropdown ajax call will be triggered ,we have to get the values from the database and  map the results to “Select2Model” class and return in json format.

In order to make this demo simple i have used assigned temporary data to select2model in real time it will come from database.

public ActionResult GetEmployeeList(string q)
        {
            
            var list = new List<Select2Model>();
 
            list.Add(new Select2Model()
            {
                text = "India",
                id = "101"
            });
            list.Add(new Select2Model()
            {
                text = "Srilanka",
                id = "102"
            });
            list.Add(new Select2Model()
            {
                text = "Singapore",
                id = "103"
            });
          
            if (!(string.IsNullOrEmpty(q) || string.IsNullOrWhiteSpace(q)))
            {
                list = list.Where(x => x.text.ToLower().StartsWith(q.ToLower())).ToList();
            }
            return Json(new { items = list }, JsonRequestBehavior.AllowGet);
        }

Finally Run the Application :

Labels: how to use select2 with ajax in asp.net, select2 with ajax source in asp.net c#, implement select2 with ajax and json





Recent Posts

Categories
Subscribe

Receive Quality Tutorials Straight in your Inbox by submitting your Email below:

Delivered by FeedBurner

Protected by Copyscape Duplicate Content Checker