Add New Values to Grid Records with AutoComplete as Editor
Environment
Product | Telerik UI for ASP.NET MVC |
Product Version | Created with version 2024.4.1112 |
Description
How can I use the ASP.NET MVC AutoComplete component as an editor in an InCell editable Grid to add new values to the Grid records?
Solution
The AutoComplete editor will provide a convenient list of options to hint the user of the available options. You can achieve this implementation through the following key steps:
-
Define an InCell editable Grid and bind its column to the complex Model property Person.
Razor@(Html.Kendo().Grid<Telerik.Examples.Mvc.Areas.GridEditingAutoCompleteNewItem.Models.GridViewModel>() .Name("grid") .Columns(columns => { columns.Bound(p => p.Person).ClientTemplate("#= data.Person ? Person.Name : '' # ").Title("AUTOCOMPLETE"); columns.Bound(p => p.Text).Title("Text"); }) .ToolBar(commands => { commands.Create().Text("New"); commands.Save(); }) .Scrollable() .HtmlAttributes(new { style = "height: 430px;" }) .Editable(editing => editing.Mode(GridEditMode.InCell)) .DataSource(dataSource => dataSource .Ajax() .ServerOperation(false) .Model(model => { model.Id(p => p.ID); }) .Update("Update", "Home") .Read("Read", "Home") .Events(e => e.Change("onChange")) ) )
-
Create a custom editor template for the column that contains an AutoComplete editor, which binds to remote data.
-
Configure the AutoComplete for server-side filtering.
Razor@model ResultEntryViewModel @(Html.Kendo().AutoCompleteFor(m => m.ID) .DataTextField("Name") .DataSource(dataSource => dataSource.Read(read => read.Action("GetAutocomplete", "Home").Data("onAdditionalData")) .ServerFiltering(true)) .Delay(500) .HighlightFirst(true) )
-
Handle the
Change
event of the Grid's DataSource and update the Person field of the respective record when its current value is changed through the AutoComplete editor. Then, trigger thecloseCell()
method of the Grid to exit edit mode.JS<script type="text/javascript"> // Handle the Grid's DataSource Change event. function onChange(e) { // The Change event provides the action argument for the type of the operation. if (e.action == "itemchange") { if (e.field == "Person") { if (typeof (e.items[0].Person) == "string") { e.items[0].set("Person", { ID: "0", Name: e.items[0].Person }); $("#grid").data("kendoGrid").closeCell($("[data-role=autocomplete]").closest("td")); } } } } function onAdditionalData() { return { text: $("#Person").val() }; } </script>
To see the complete example, refer to the ASP.NET MVC project on how to add a new value to the Grid records when the Grid uses the Telerik UI AutoComplete as an editor.