Highlight Matched Characters in ASP.NET MVC DropDownList

21 Aug 20263 minutes to read

Use the highlightSearch method to highlight the matched characters in DropDownList filtering. The highlightSearch method accepts the following parameters: item (the list item element), query (the search string to highlight), ignoreCase (boolean, whether to ignore case when matching), and filterType (the matching strategy, e.g., StartsWith, Contains, EndsWith). The method is typically called from the itemCreated event of the DropDownList fields, using the search string captured in the filtering event handler, and the filtered data is refreshed via updateData.

@Html.EJS().DropDownList("customers").Placeholder("Select a customer").Filtering("filtering").PopupHeight("200px").DataSource(dataManger =>
            dataManger.Url("https://services.odata.org/V4/Northwind/Northwind.svc/").Adaptor("ODataV4Adaptor").CrossDomain(true)).AllowFiltering(true).Fields(new Syncfusion.EJ2.DropDowns.DropDownListFieldSettings
            {
                Value = "CustomerID", Text = "ContactName"
            }).Query("new ej.data.Query().from('Customers').select(['ContactName', 'CustomerID']).take(6)").Render()
<script>
    var queryString;
    document.addEventListener('DOMContentLoaded', function () {
        var ddlObj = document.getElementById("customers")
        ddlObj.ej2_instances[0].fields = {
            text: "ContactName", value: "CustomerID", itemCreated: function (e) {
                new ej.dropdowns.highlightSearch(e.item, queryString, true, 'StartsWith');
            }
        }
    }, false);
    function filtering(e) {
        var data = document.getElementById('customers').ej2_instances[0];
        // take text for highlight the character in list items.
        queryString = e.text;
        var query = new ej.data.Query().from('Customers').select(['ContactName', 'CustomerID']).take(6);
        //frame the query based on search string with filter type.
        query = (e.text !== '') ? query.where('ContactName', 'StartsWith', e.text, true) : query;
        //pass the filter data source, filter query to updateData method.
        e.updateData(data.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 DropDownListController : Controller
    {
        public IActionResult highlight()
        {           
            return View();
        }
    }
}