Filtering in ASP.NET MVC MultiSelect

28 Aug 202615 minutes to read

The MultiSelect has built-in support to filter data items when allowFiltering is enabled. The filter operation starts as soon as you start typing characters in the MultiSelect input.

To display filtered items in the popup, filter the required data and return it to the MultiSelect via the updateData method by using the filtering event.

The following sample illustrates how to query the data source and pass the data to the MultiSelect through the updateData method in the filtering event.

@Html.EJS().MultiSelect("country").Placeholder("Select a COuntry").PopupHeight(
                   "230px").DataSource((IEnumerable<object>)ViewBag.data).AllowFiltering(true).Filtering("onfiltering").Fields(new Syncfusion.EJ2.DropDowns.MultiSelectFieldSettings { Value = "Name" }).Render()

<script>
    function onfiltering(e) {
         var query = new ej.data.Query();
            query = (e.text !== '') ? query.where('Name', 'startswith', e.text, true) : query;
            e.updateData(@Html.Raw(JsonConvert.SerializeObject(ViewBag.data)), query)
    }
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
    public class Countries
    {
        public string Name { get; set; }
        public string Code { get; set; }
        public List<Countries> CountriesList()
        {
            List<Countries> country = new List<Countries>();
            country.Add(new Countries { Name = "Australia", Code = "AU" });
            country.Add(new Countries { Name = "Bermuda", Code = "BM" });
            country.Add(new Countries { Name = "Canada", Code = "CA" });
            country.Add(new Countries { Name = "Cameroon", Code = "CM" });
            country.Add(new Countries { Name = "Denmark", Code = "DK" });
            country.Add(new Countries { Name = "France", Code = "FR" });
            country.Add(new Countries { Name = "Finland", Code = "FI" });
            country.Add(new Countries { Name = "Germany", Code = "DE" });
            country.Add(new Countries { Name = "Greenland", Code = "GL" });
            country.Add(new Countries { Name = "Hong Kong", Code = "HK" });
            country.Add(new Countries { Name = "India", Code = "IN" });
            country.Add(new Countries { Name = "Italy", Code = "IT" });
            country.Add(new Countries { Name = "Japan", Code = "JP" });
            country.Add(new Countries { Name = "Mexico", Code = "MX" });
            country.Add(new Countries { Name = "Norway", Code = "NO" });
            country.Add(new Countries { Name = "Poland", Code = "PL" });
            country.Add(new Countries { Name = "Switzerland", Code = "CH" });
            country.Add(new Countries { Name = "United Kingdom", Code = "GB" });
            country.Add(new Countries { Name = "United States", Code = "US" });
            return country;
        }
    }
}

Limit the minimum filter character

When filtering list items, you can set a minimum character count before a remote request is raised to fetch filtered data on the MultiSelect. Do this with manual validation in the filter event handler.

In the following example, the remote request does not fetch the search data until the search key contains three characters.

@Html.EJS().MultiSelect("customers").Placeholder("Select a customer").Filtering("onfiltering").AllowFiltering(true).PopupHeight("200px").DataSource(obj => obj.Url("https://services.odata.org/V4/Northwind/Northwind.svc/").Adaptor(
        "ODataV4Adaptor").CrossDomain(true)).Fields(new Syncfusion.EJ2.DropDowns.MultiSelectFieldSettings { Text = "ContactName", Value = "CustomerID" }).Query("new ej.data.Query().from('Customers').select(['ContactName', 'CustomerID']).take(6)").Render()

<script>
    function onfiltering(e) {
        var CBObj = document.getElementById("customers").ej2_instances[0];
        // load overall data when search key empty.
        if (e.text == '' && e.text.length < 3) {
            e.updateData(CBObj.dataSource);
        }
        let query = new ej.data.Query().from('Customers').select(['ContactName', 'CustomerID']).take(6);
        query = (e.text !== '' && e.text.length >= 3) ? query.where('ContactName', 'startswith', e.text, true) : query;
        e.updateData(CBObj.dataSource, query);
    }
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    public class MultiSelectController : Controller
    {
        public ActionResult filterlimit()
        {
            return View();
        }
    }
}

Change the filter type

While filtering, you can change the filter type to contains, startsWith, or endsWith for string-typed fields within the filter event handler.

In the following examples, data filtering is done with the endsWith type.

@Html.EJS().MultiSelect("customers").Placeholder("Select a customer").AllowFiltering(true).Filtering("onfiltering").PopupHeight("200px").DataSource(obj => obj.Url("https://services.odata.org/V4/Northwind/Northwind.svc/").Adaptor(
        "ODataV4Adaptor").CrossDomain(true)).Fields(new Syncfusion.EJ2.DropDowns.MultiSelectFieldSettings { Text = "ContactName", Value = "CustomerID" }).Query("new ej.data.Query().from('Customers').select(['ContactName', 'CustomerID']).take(6)").Render()

<script>
    function onfiltering(e) {
        var CBObj = document.getElementById("customers").ej2_instances[0];
        // load overall data when search key empty.
        if (e.text == '')
            e.updateData(CBObj.dataSource);
        else {
            var query = new ej.data.Query().from('Customers').select(['ContactName', 'CustomerID']).take(6);
            query = (e.text !== '') ? query.where('ContactName', 'endswith', e.text, true) : query;
            e.updateData(CBObj.dataSource, query);
        }
    }
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    public class MultiSelectController : Controller
    {
        public ActionResult filtertype()
        {
            return View();
        }       
    }
}

Case-sensitive filtering

Data items can be filtered either with or without case sensitivity using the DataManager. Do this by passing the fourth optional parameter of the where clause.

The following example shows how to perform a case-sensitive filter.

@Html.EJS().MultiSelect("customers").Placeholder("Select a customer").Filtering("onfiltering").AllowFiltering(true).PopupHeight("200px").DataSource(obj => obj.Url("https://services.odata.org/V4/Northwind/Northwind.svc/").Adaptor(
        "ODataV4Adaptor").CrossDomain(true)).Fields(new Syncfusion.EJ2.DropDowns.MultiSelectFieldSettings { Text = "ContactName", Value = "CustomerID" }).Query("new ej.data.Query().from('Customers').select(['ContactName', 'CustomerID']).take(6)").Render()

<script>
    function onfiltering(e) {
        var CBObj = document.getElementById("customers").ej2_instances[0];
        // load overall data when search key empty.
        if (e.text == '')
            e.updateData(CBObj.dataSource);
        else {
            var query = new ej.data.Query().from('Customers').select(['ContactName', 'CustomerID']).take(6);
            query = (e.text !== '') ? query.where('ContactName', 'startswith', e.text, false) : query;
            e.updateData(CBObj.dataSource, query);
        }
    }
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    public class MultiSelectController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }       
    }
}

Diacritics filtering

The MultiSelect supports diacritics filtering, which ignores diacritics and makes it easier to filter results in lists that contain international characters when ignoreAccent is enabled.

In the following sample, data with diacritics are bound as the data source for the MultiSelect.

@Html.EJS().MultiSelect("list").DataSource((string[])ViewBag.data).Placeholder("e.g: aero").IgnoreAccent(true).AllowFiltering(true).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    public class MultiSelectController : Controller
    {
        public ActionResult diacritics()
        {
            ViewBag.data = new string[] { "Aeróbics", "Aeróbics en Agua", "Aerografía", "Aeromodelaje", "Águilas", "Ajedrez", "Ala Delta", "Álbumes de Música","Alusivos", "Análisis de Escritura a Mano"  };
            return View();
        }       
    }
}

Debounce delay

Use the debounceDelay property to set a delay, in milliseconds, for filtering. This reduces the frequency of filtering as you type and improves performance and responsiveness. The default DebounceDelay is 300 ms. Set it to 0 to disable the delay entirely.

@Html.EJS().MultiSelect("default").Placeholder("Select games").DataSource((IEnumerable<object>)ViewBag.data).DebounceDelay(300).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    public class MultiSelectController : Controller
    {
        public ActionResult arrayofstrings()
        {
            ViewBag.data = new string[] { "Badminton", "Basketball", "Cricket", "Football", "Golf", "Gymnastics", "Hockey", "Tennis" };
            return View();
        }
    }
}

See also