I am writing this article mainly because I have not found many articles on binding data using a Kendo dropdown list with server-side filtering and searching. In this article, we are using ASP.NET MVC. We can use the same logic to apply for ASP.NET as well.
Step 1
Create a table for Country or other kinds as per your requirement, which holds both text and value to display items in the drop-down list. Here, I’m using some method which returns a country list as a data source.
Step 2
Create one ASP.NET MVC/ASP.NET project. Here, I’m using an ASP.NET MVC Application to demonstrate. I’m creating one controller to display the Kendo drop-down list.
Step 3
To access the predefined functionality from Kendo UI, we need to add the following scripts and CSS in our application. So, just add the below references in your project.
- <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.common.min.css" />
- <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.silver.min.css" />
- <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.mobile.all.min.css" />
- <script src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
- <script src="http://kendo.cdn.telerik.com/2017.1.118/js/kendo.all.min.js"></script>
Step 4
I have created an empty controller and named it as Country.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace Demo.Controllers {
- public class CountryController: Controller {
-
- public ActionResult Index() {
- return View();
- }
- }
- }
Step 5
Now, add a View for this action method and add the below code to it which will render the Kendo dropdown to the input element.
- <input id="ddlcountries" style="width: 100%;" />
Step 6
Create one method in the controller which will return a list of countries that should contain a format that has both, text and value.
- public class Country
- {
- public string Code { get; set; }
- public string EnglishName {get;set;}
- }
In the above code, I have created one class which will hold the properties of country as code and EnglishName which is considered as text and value.
- public static List<Country> Countries = new List<Country>
- {
- new Country {Code = "IN", EnglishName = "India"},
- new Country {Code = "AU", EnglishName = "Australia"},
- new Country {Code = "SE", EnglishName = "Sweden"},
- };
The above method returns the list of countries which we are going to use as our data source.
Step 7
Create one action method which will filter and search the data based on the page size sent from JavaScript and this method will return the filtered result in JSON format.
- public JsonResult GetCountries()
- {
- int pageSize = Convert.ToInt32(Request.Params.Get("pageSize"));
- int skip = Convert.ToInt32(Request.Params.Get("skip"));
- string search = Request.Params.Get("filter[filters][0][value]");
- var countriesList = Countries ;
- var total = countriesList.Count();
- var data = countriesList.Skip(skip).Take(pageSize).ToList();
- if (!string.IsNullOrEmpty(search) && !string.IsNullOrWhiteSpace(search))
- {
- var result = countriesList.Where(x => x.EnglishName.ToString().ToLower().Contains(search.ToLower())).ToList();
- total = result.Count;
- return Json(new { total = total, data = result }, JsonRequestBehavior.AllowGet);
-
- }
- return Json(new { total = total, data = data }, JsonRequestBehavior.AllowGet);
- }
The above method will receive page size, search parameters from the request. We will capture these input parameters and send to the method to receive the output in JSON format.
Step 8
Now, add the below script to load data to Kendo drop-down list.
- $("#ddlcountries").kendoDropDownList({
- dataTextField: "EnglishName",
- dataValueField: "Code",
- noDataTemplate: 'No Data!',
- filter: "contains",
- minLength: 2,
- virtual: {
- itemHeight: 26,
- valueMapper: function (options) {
- $.ajax({
- url: '/CountriesValueMapper',
- type: "GET",
- dataType: "jsonp",
- data: convertValues(options.value),
- success: function (data) {
- options.success(data);
- }
- })
- }
- },
- height: 75,
- dataSource: {
- transport: {
- read: function (options) {
- $.ajax({
- url: '/GetCountries',
- contentType: 'application/json',
- dataType: 'json',
- type: 'GET',
- data: options.data,
- success: function (result) {
- options.success(result);
- }
- })
- }
- },
- schema: {
- data: 'data',
- total: 'total',
- fields: [
- { field: 'EnglishName', type: 'string' },
- { field: 'Code', type: 'string' },
- ]
- },
- pageSize: 11,
- Type: "aspnetmvc-ajax",
- serverPaging: true,
- serverFiltering: true
- },
- optionLabel: {
- EnglishName: "Select",
- Code: "0",
- },
- index: 0
- });
Detailed Explanation
- ‘ddlcountries’ is the id of the input element that we are going to render the drop-down list.
- dataTextField, dataValueField we need to bind the text and value to the drop-down list.
- filter: "contains", here, we can apply other combinations as well like ‘startswith’, but make sure the same kind of filter needs to be applied from the back-end in order to filter the result
- minLength is when we search for text in the textbox of the drop-down list. Here, if we specify length 2 after typing two characters, it will start searching for those in the database.
- valueMapper: this is important. It is a normal AJAX call. Here, we are passing the selected value as input to the backend will return the selected element id. It will check from the database and return the current element id.
- In the data source, we are making the server side method that we have written earlier.
- In the schema, we need to add the server returned columns in JSON format.
- page Size. Here, we can specify the on default how many records need to be fetched and displayed initially, based on the page size remaining records are fetched
- serverPaging, serverFiltering needs to be mentioned if we want server side filtering
Step 9
Create one action method named CountriesValueMapper which will return the selected item index.
- public JsonResult CountriesValueMapper(int[] values)
- {
- var indices = new List<int>();
- var countryList = Countries ;
-
- if (values != null && values.Any())
- {
- var index = 0;
-
- foreach (var item in countryList)
- {
- if (values.Contains(item.Code))
- {
- indices.Add(index);
- }
- index += 1;
- }
- }
- return Json(indices, JsonRequestBehavior.AllowGet);
- }
Step 10
In order to pass the input parameter from AJAX call, we need to convert into a specific format in order to pass to server side function. Please add the below function in JavaScript code, which will convert into a specific format.
- var data = {};
-
- value = $.isArray(value) ? value : [value];
-
- for (var idx = 0; idx < value.length; idx++) {
- data["values[" + idx + "]"] = value[idx];
- }
-
- return data;
Step 11
Save and run this. It will render the drop-down list with server-side filtering and searching.