This example shows how to define action in controller to delete rows from database by handling Edit request of CollectionViewHelper.
The following image shows how the FlexGrid appears after the CollectionViewEditRequest is used in the controller.
The example uses C1NWind datasource, which was configured in the application in the Quick Start. To delete a row, click the row header to select the row, and click Delete button on the keyboard. The selected row is deleted and the source database is updated accordingly.
The following code demonstrates how to handle CollectionViewEditRequest to enable deleting of a record in the FlexGrid:
DeleteController.cs
C# |
Copy Code
|
---|---|
//Define datasource for FlexGrid private C1NWindEntities db = new C1NWindEntities(); public ActionResult Index() { return View(db); } //Instantiate a JSON request public ActionResult GridDeleteCategory([C1JsonRequest]CollectionViewEditRequest<Category> requestData) { return Delete(requestData, db.Categories, item => item.CategoryID); } private ActionResult Delete<T>(CollectionViewEditRequest<T> requestData, DbSet<T> data, Func<T, object> getKey) where T : class { return this.C1Json(CollectionViewHelper.Edit<T>(requestData, item => { string error = string.Empty; bool success = true; try { var resultItem = data.Find(getKey(item)); data.Remove(resultItem); db.SaveChanges(); } catch (DbEntityValidationException e) { error = string.Join(",", e.EntityValidationErrors.Select(result => { return string.Join(",", result.ValidationErrors.Select(err => err.ErrorMessage)); })); success = false; } catch (Exception e) { error = e.Message; success = false; } return new CollectionViewItemResult<T> { Error = error, Success = success && ModelState.IsValid, Data = item }; }, () => data.ToList<T>())); } |
In this example, the Delete action is assigned to the Delete property of FlexGrid's ItemSource.
Delete.cshtml
HTML |
Copy Code
|
---|---|
<c1-flex-grid id="fGDelCView" auto-generate-columns="false" is-read-only="true" allow-delete="true"> <c1-items-source delete-action-url="@Url.Action("GridDeleteCategory")"></c1-items-source> <c1-flex-grid-column binding="CategoryID"></c1-flex-grid-column> <c1-flex-grid-column binding="CategoryName"></c1-flex-grid-column> <c1-flex-grid-column binding="Description" width="*"></c1-flex-grid-column> </c1-flex-grid> |