Implementing AutoComplete with Server Filtering in the Filter Component
Environment
Product | Telerik UI for ASP.NET Core Filter |
Progress Telerik UI for ASP.NET Core version | Created with the 2023.3.1114 version |
Description
How can I define the AutoComplete component with server filtering as a custom editor of a specified Telerik UI for ASP.NET Core Filter field?
Solution
-
Define a field within the
Fields()
configuration and use theEditorTemplateHandler()
option to specify the JavaScript function that will return the AutoComplete editor.@(Html.Kendo().Filter<Kendo.Mvc.Examples.Models.ProductViewModel>() .Name("filter") .ApplyButton(true) .DataSource("dataSource1") .Fields(f => { f.Add(p=>p.ProductName).Label("Product Name").EditorTemplateHandler("productNameAutoCompleteEditor"); }) )
@addTagHelper *, Kendo.Mvc <kendo-filter name="filter" apply-button="true" datasource-id="dataSource1"> <fields> <filter-field name="ProductName" type="string" label="Product Name" editor-template-handler="productNameAutoCompleteEditor"> </filter-field> </fields> </kendo-filter>
Initialize the AutoComplete editor within the productNameAutoCompleteEditor handler.
- Handle the
filtering
event of the AutoComplete, extract the search entry value from the event data, and store it into a global variable searchParameter. -
Use the
data
option of the DataSource to pass the global variable as an additional parameter through theRead
request of the AutoComplete. This way, you will ensure that the correct search entry will be sent to the server when the Filter component has multiple fields that use the same AutoComplete editor.function productNameAutoCompleteEditor(container, options) { var searchParameter = ""; $('<input data-bind="value: value" name="' + options.field + '"/>') .appendTo(container) .kendoAutoComplete({ minLength: 3, placeholder: "Please type at least 3 characters.", filter: "contains", filtering: function(e) { searchParameter = e.filter.value; // Get the search entry from the event data. }, dataTextField: "ProductName", dataSource: { serverFiltering: true, transport: { read: { url: '@Url.Action("GetItems","Home")', data: function () { return { search: searchParameter }; } } } } }); }
public JsonResult GetItems(string search) { using (var northwind = GetContext()) { var products = northwind.Products.Select(product => new ProductViewModel { ProductID = product.ProductID, ProductName = product.ProductName }); if (!string.IsNullOrEmpty(search)) { products = products.Where(p => p.ProductName.Contains(search)).ToList(); } return Json(products); } }
For a runnable example based on the code above, refer to the following REPL samples: