Inline Editing
You can define commands and set the edit mode to configure the Telerik UI Grid for ASP.NET Core for inline editing.
For runnable examples, refer to the demos on implementing the editing approaches in the Grid.
Defining a Schema.Model.Id is mandatory for the proper execution of the Update, Create and Destroy of the Grid.
Setting the Inline Edit Mode
-
Add a new class to the
~/Models
folder. The following example uses theProductViewModel
name.public class ProductViewModel { public int ProductID { get; set; } // The ProductName property is required. [Required] public string ProductName { get; set; } // Use the Integer editor template for the UnitsInStock property. [UIHint("Integer")] public short? UnitsInStock { get; set; } }
-
Open
HomeController.cs
and add a new action method which will return the Products as JSON. The Grid will make Ajax requests to this action.public ActionResult Products_Read([DataSourceRequest]DataSourceRequest request) { // ToDataSourceResult works with IEnumerable and IQueryable. using (var northwind = new NorthwindEntities()) { IQueryable<Product> products = northwind.Products; DataSourceResult result = products.ToDataSourceResult(request); return Json(result); } }
-
Add a new action method to
HomeController.cs
. It will be responsible for saving the new data items. Name the methodProducts_Create
.public ActionResult Products_Create([DataSourceRequest]DataSourceRequest request, ProductViewModel product) { if (ModelState.IsValid) { using (var northwind = new NorthwindEntities()) { // Create a new Product entity and set its properties from the posted ProductViewModel. var entity = new Product { ProductName = product.ProductName, UnitsInStock = product.UnitsInStock }; // Add the entity. northwind.Products.Add(entity); // Insert the entity in the database. northwind.SaveChanges(); // Get the ProductID generated by the database. product.ProductID = entity.ProductID; } } // Return the inserted product. The Grid needs the generated ProductID. Also return any validation errors. return Json(new[] { product }.ToDataSourceResult(request, ModelState)); }
-
Add a new action method to
HomeController.cs
. It will be responsible for saving the updated data items. Name the methodProducts_Update
.public ActionResult Products_Update([DataSourceRequest]DataSourceRequest request, ProductViewModel product) { if (ModelState.IsValid) { using (var northwind = new NorthwindEntities()) { // Create a new Product entity and set its properties from the posted ProductViewModel. var entity = new Product { ProductID = product.ProductID, ProductName = product.ProductName, UnitsInStock = product.UnitsInStock }; // Attach the entity. northwind.Products.Attach(entity); // Change its state to Modified so Entity Framework can update the existing product instead of creating a new one. northwind.Entry(entity).State = EntityState.Modified; // Or use ObjectStateManager if using a previous version of Entity Framework. // northwind.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified); // Update the entity in the database. northwind.SaveChanges(); } } // Return the updated product. Also return any validation errors. return Json(new[] { product }.ToDataSourceResult(request, ModelState)); }
-
Add a new action method to
HomeController.cs
. It will be responsible for saving the deleted data items. Name the methodProducts_Destroy
.public ActionResult Products_Destroy([DataSourceRequest]DataSourceRequest request, ProductViewModel product) { if (ModelState.IsValid) { using (var northwind = new NorthwindEntities()) { // Create a new Product entity and set its properties from the posted ProductViewModel. var entity = new Product { ProductID = product.ProductID, ProductName = product.ProductName, UnitsInStock = product.UnitsInStock }; // Attach the entity. northwind.Products.Attach(entity); // Delete the entity. northwind.Products.Remove(entity); // Or use DeleteObject if using a previous versoin of Entity Framework. // northwind.Products.DeleteObject(entity); // Delete the entity in the database. northwind.SaveChanges(); } } // Return the removed product. Also return any validation errors. return Json(new[] { product }.ToDataSourceResult(request, ModelState)); }
-
In the view, configure the Grid to use the action methods that were created in the previous steps. The
Create
,Update
, andDestroy
action methods have to return a collection with the modified or deleted records which will enable the DataSource to apply the changes accordingly. TheCreate
method has to return a collection of the created records with the assigned ID field.@(Html.Kendo().Grid<KendoGridAjaxEditing.Models.ProductViewModel>() .Name("grid") .Columns(columns => { columns.Bound(product => product.ProductID).Width(100); columns.Bound(product => product.ProductName); columns.Bound(product => product.UnitsInStock).Width(250); columns.Command(commands => { commands.Edit(); // The "edit" command will edit and update data items. commands.Destroy(); // The "destroy" command removes data items. }).Title("Commands").Width(200); }) .ToolBar(toolbar => toolbar.Create()) // The "create" command adds new data items. .Editable(editable => editable.Mode(GridEditMode.InLine)) // Use the inline edit mode. .DataSource(dataSource => dataSource.Ajax() .Model(model => { model.Id(product => product.ProductID); // Specify the property which is the unique identifier of the model. model.Field(product => product.ProductID).Editable(false); // Make the ProductID property not editable. }) .Create(create => create.Action("Products_Create", "Home")) // Action invoked when the user saves a new data item. .Read(read => read.Action("Products_Read", "Home")) // Action invoked when the Grid needs data. .Update(update => update.Action("Products_Update", "Home")) // Action invoked when the user saves an updated data item. .Destroy(destroy => destroy.Action("Products_Destroy", "Home")) // Action invoked when the user removes a data item. ) .Pageable() )
<kendo-grid name="grid" height="430"> <datasource type="DataSourceTagHelperType.Ajax" page-size="20"> <schema data="Data" total="Total"> <model id="ProductID"> <fields> <field name="ProductID" editable="false"></field> </fields> </model> </schema> <transport> <read url=@Url.Action("Products_Create", "Home") /> <update url=@Url.Action("Products_Update", "Home") /> <create url=@Url.Action("Products_Create", "Home") /> <destroy url=@Url.Action("Products_Destroy", "Home") /> </transport> </datasource> <columns> <column field="ProductID" width="100"/> <column field="ProductName" /> <column field="UnitsInStock" width="250" /> <column width="200" title="Commands"> <commands> <column-command text="Edit" name="edit"></column-command> <column-command text="Delete" name="destroy"></column-command> </commands> </column> </columns> <toolbar> <toolbar-button name="create"></toolbar-button> </toolbar> <editable mode="inline" /> <pageable enabled="true" /> </kendo-grid>
-
The Grid component serializes editors allocated within the
~/Views/Shared/EditorTemplates
folder. If no editors are available in that folder, the Grid will revert to using a default editor based on the primitive type. To define a custom editor for a specified column, add the view that contains the editor in the~/Views/Shared/EditorTemplates
folder and specify the view name in theEditorTemplateName()
option of the column.@(Html.Kendo().Grid<KendoGridAjaxEditing.Models.ProductViewModel>() .Name("grid") .Columns(columns => { ... columns.Bound(product => product.ProductName).EditorTemplateName("ProductNameEditor"); ... }) // Other configuration. )
//~/Views/Shared/EditorTemplates/ProductNameEditor.cshtml @model string @(Html.Kendo().TextAreaFor(model => model) .HtmlAttributes(new { data_bind = "value: ProductName"}) .Rows(3) )
<kendo-grid name="grid" height="430"> <columns> ... <column field="ProductName"> <column-editor-template> <kendo-textarea name="ProductName" rows="3"> </kendo-textarea> </column-editor-template> </column> ... </columns> <!--Other configuration--> </kendo-grid>
For more information on creating editors for the Grid columns, see the Editor Templates article.
Handling ModelState Errors
When editing is performed, server validation is often needed. This section demonstrates how to use the AddModelError
method with the Telerik UI Grid for ASP.NET Core.
- Perform all steps from the previous section.
-
Add some validation code to the
Products_Update
method. For example, check the length of theProductName
property.public ActionResult Products_Update([DataSourceRequest]DataSourceRequest request, ProductViewModel product) { if (product.ProductName.Length < 3) { ModelState.AddModelError("ProductName", "ProductName should be at least three characters long."); } if (ModelState.IsValid) { using (var northwind = new NorthwindEntities()) { // Create a new Product entity and set its properties from the posted ProductViewModel. var entity = new Product { ProductID = product.ProductID, ProductName = product.ProductName, UnitsInStock = product.UnitsInStock }; // Attach the entity. northwind.Products.Attach(entity); // Change its state to Modified so Entity Framework can update the existing product instead of creating a new one. northwind.Entry(entity).State = EntityState.Modified; // Or use ObjectStateManager if using a previous version of Entity Framework. // northwind.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified); // Update the entity in the database. northwind.SaveChanges(); } } // Return the updated product. Also return any validation errors. return Json(new[] { product }.ToDataSourceResult(request, ModelState)); }
Subscribe to the
DataSource.Error()
event handler. it is fired when model state errors or other unexpected problem occur when making the ajax request. in the event handler, display the errors and call thecancelchanges
method of the Grid.
@(Html.Kendo().Grid<KendoGridAjaxEditing.Models.ProductViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(product => product.ProductID).Width(100);
columns.Bound(product => product.ProductName);
columns.Bound(product => product.UnitsInStock).Width(250);
columns.Command(commands =>
{
commands.Edit();
commands.Destroy();
}).Title("Commands").Width(200);
})
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.InLine))
.DataSource(dataSource =>
dataSource.Ajax()
.Events(events => events.Error("grid_error")) // Handle the "error" event.
.Model(model =>
{
model.Id(product => product.ProductID);
model.Field(product => product.ProductID).Editable(false);
})
.Create(create => create.Action("Products_Create", "Home"))
.Read(read => read.Action("Products_Read", "Home"))
.Update(update => update.Action("Products_Update", "Home"))
.Destroy(destroy => destroy.Action("Products_Destroy", "Home"))
)
.Pageable()
)
<kendo-grid name="grid" height="430">
<datasource type="DataSourceTagHelperType.Ajax" page-size="20"
on-error="grid_error">
<schema data="Data" total="Total">
<model id="ProductID">
<fields>
<field name="ProductID" editable="false"></field>
</fields>
</model>
</schema>
<transport>
<read url=@Url.Action("Products_Create", "Home") />
<update url=@Url.Action("Products_Update", "Home") />
<create url=@Url.Action("Products_Create", "Home") />
<destroy url=@Url.Action("Products_Destroy", "Home") />
</transport>
</datasource>
<columns>
<column field="ProductID" width="100"/>
<column field="ProductName" />
<column field="UnitsInStock" width="250" />
<column width="200" title="Commands">
<commands>
<column-command text="Edit" name="edit"></column-command>
<column-command text="Delete" name="destroy"></column-command>
</commands>
</column>
</columns>
<toolbar>
<toolbar-button name="create"></toolbar-button>
</toolbar>
<editable mode="inline" />
<pageable enabled="true" />
</kendo-grid>
<script>
function grid_error(e) {
if (e.errors) {
var message = "There are some errors:\n";
// Create a message containing all errors.
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function () {
message += this + "\n";
});
}
});
// Display the message.
alert(message);
// Cancel the changes.
var grid = $("#grid").data("kendoGrid");
grid.cancelChanges();
}
}
</script>
Runnable Samples
To check and download runnable samples demonstrating Inline editing, you can go to these resources: