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
Razor |
Copy Code
|
---|---|
@(Html.C1().FlexGrid().Id("fGRCView").AutoGenerateColumns(false).AllowAddNew(true) .AllowSorting(true).CssClass("grid") .Columns(columns => columns .Add(c => c.Binding("CategoryID")) .Add(c => c.Binding("CategoryName")) .Add(c => c.Binding("Description").Width("500"))) .Bind(ib => ib.Bind(Model.Categories) .Create(Url.Action("GridCreateCategory")) ) ) |