CollectionView supports various server-side operations, including creating, reading, updating, deleting and editing of the field in data-bound controls, such as FlexGrid.
This example shows how to use Edit request of CollectionViewHelper, which allows adding records to source database in data-bound controls, such as FlexGrid. Here, the GridCreateCategory action of the controller is assigned to the Create property of FlexGrid's ItemSource.
The following image shows how the FlexGrid appears after the AllowAddNew property is set to true, and CollectionViewEditRequest is used in the controller.
The example uses C1NWind datasource, which was configured in the application in the Quick Start:
The following code example demonstrates how to use Create property of FlexGrid's ItemSource and CollectionViewEditRequest to enable creation of a record in the FlexGrid:
CreateController.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 GridReadCategory([C1JsonRequest] CollectionViewRequest<Category> requestData) { return this.C1Json(CollectionViewHelper.Read(requestData, db.Categories)); } public ActionResult GridCreateCategory([C1JsonRequest]CollectionViewEditRequest<Category> requestData) { var category = requestData.OperatingItems.First(); if (category.CategoryName == null) { category.CategoryName = ""; } return Create(requestData, db.Categories); } private ActionResult Create<T>(CollectionViewEditRequest<T> requestData, DbSet<T> data) where T : class { return this.C1Json(CollectionViewHelper.Edit<T>(requestData, item => { string error = string.Empty; bool success = true; try { data.Add(item); 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 GridCreateCategory action is assigned to the Create property of FlexGrid's ItemSource.
Create.cshtml
HTML |
Copy Code
|
---|---|
<c1-flex-grid id="fGRCView" auto-generate-columns="false" is-read-only="true" allow-add-new="true" allow-sorting="true" class="grid"> <c1-items-source create-action-url="@Url.Action("GridCreateCategory")"></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="500"></c1-flex-grid-column> </c1-flex-grid> |