In this post I am going to explain how to create a Kendo Grid with CRUD operations. I came across this requirementin one of my project that i need to load a table records in a grid view and to perform all CRUD operations in it.
First, create an empty solution in visual studio. I am naming my solution as “KendoGridCRUD_Mvc“. Right click the solution name in the solution explorer and add a new Project under Visual C# => Web => ASP.NET Web Application
Type a name in the project name and Click Ok. In our case the project name is “KendoGridCRUD“. Select MVC in the next screen and click OK.
Now our solution looks like below.
To use Kendo Grid in our project, in his example i am going to use Telerik’s CDN to refer to the style sheets and Javascripts in our project.
In the Layout page , add the scripts to use Kendo Grid in our project. Add the below URL’s in the project to use Kendo Grid in the Views.
<link href="http://cdn.kendostatic.com/2014.3.1119/styles/kendo.common.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2014.3.1119/styles/kendo.mobile.all.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2014.3.1119/styles/kendo.dataviz.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2014.3.1119/styles/kendo.default.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2014.3.1119/styles/kendo.dataviz.default.min.css" rel="stylesheet" type="text/css" />
<script src="http://cdn.kendostatic.com/2014.3.1119/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.3.1119/js/jszip.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.3.1119/js/kendo.all.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.3.1119/js/kendo.aspnetmvc.min.js"></script>
Now that we have referenced Kendo Grid in our project, its time for the coding part.
Add the below code in your View(The page where the Grid view will be displayed)
@(Html.Kendo().Grid<ARMS_WebApi.ViewModel.ComponentTypes>()
.Name("EditComponentsGrid")
.Columns(col =>
{
col.Template(x => { }).ClientTemplate("<input type='checkbox' id='chkSelect_#= ComponentTypeID#' userId='#= ComponentTypeID#' />").Width(10);
col.Bound(m => m.ComponentTypeID).Hidden(true);
col.Bound(m => m.ComponentTypeDescription).Width(150).Title("Component Type");
col.Command(cmd =>
{
cmd.Destroy();
}).Width(25);
})
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.InCell).CreateAt(GridInsertRowPosition.Top))
.Pageable()
.Sortable()
.Scrollable(scr => scr.Height(300))
.Filterable(filterable => filterable
.Extra(false)
.Operators(op => op.ForString(str => str.Clear()
.StartsWith("Starts with")
.IsEqualTo("Is equal to")
.IsNotEqualTo("Is not equal to")
.Contains("Contains")
))
)
.Resizable(re => re.Columns(false))
.Reorderable(reo => reo.Columns(false))
.DataSource(ds => ds.Ajax()
.Batch(true)
.Model(mod =>
{
mod.Id(com => com.ComponentTypeID);
})
//.Create(create => create.Action("ComponentType_Create", "ComponentType"))
.Read(read => read.Action("ComponentType_Read", "ComponentType"))
.Update(update => update.Action("ComponentType_Update", "ComponentType"))
.Destroy(destroy => destroy.Action("ComponentType_Delete", "ComponentType"))
))
We have two buttons above the grid for saving the grid and to export the grid to excel. Export grid works only for the current page listed in the grid.
Below is the Javascript code for the button click action.
<button onclick="sendData()" name="btnSaveGrid" id="btnSaveGrid" class="btn btn-success"><span class="glyphicon glyphicon-floppy-disk"></span> Save Changes</button>
<button class="btn btn-primary" id="btnExcelExport"><span class="glyphicon glyphicon-file"></span> Excel</button>
The sendData method finds all the changes made to the grid and passes the changes to the Controller Action with three parameters.
function sendData() {
var grid = $("#EditComponentsGrid").data("kendoGrid"),
parameterMap = grid.dataSource.transport.parameterMap;
//get the new and the updated records
var currentData = grid.dataSource.data();
var updatedRecords = [];
var newRecords = [];
for (var i = 0; i < currentData.length; i++) {
if (currentData[i].isNew()) {
//this record is new
newRecords.push(currentData[i].toJSON());
} else if (currentData[i].dirty) {
updatedRecords.push(currentData[i].toJSON());
}
}
//this records are deleted
var deletedRecords = [];
for (var i = 0; i < grid.dataSource._destroyed.length; i++) {
deletedRecords.push(grid.dataSource._destroyed[i].toJSON());
}
var data = {};
$.extend(data, parameterMap({ updated: updatedRecords }), parameterMap({ deleted: deletedRecords }), parameterMap({ new: newRecords }));
$.ajax({
url: "/ComponentType/UpdateCreateDelete",
data: data,
type: "POST",
error: function () {
//Handle the server errors using the approach from the previous example
},
success: function () {
alert("update on server is completed");
grid.dataSource._destroyed = [];
//refresh the grid - optional
grid.dataSource.read();
}
})
The corresponding action method in the controller which will be called by the javascript method through an AJAX call.
public ActionResult UpdateCreateDelete(
[Bind(Prefix = "updated")]List<ComponentTypes> updatedComponentTypes,
[Bind(Prefix = "new")]List<ComponentTypes> newComponentTypes,
[Bind(Prefix = "deleted")]List<ComponentTypes> deletedComponentTypes)
{
if (updatedComponentTypes != null)
{
//save to the database
}
if (newComponentTypes != null )
{
//save to the database
}
if (deletedComponentTypes != null)
{
//save to the database
}
return Json("Success");
}
Thus in this post we saw how to load a kendo grid with data . I have used the kendo grid as a batch editing grid in this example. (Batch(true)). We made changes to the grid by add, edit ,delete and finally saved all changed to the database on a single button click.
In the case of bulk inserting entity framework is very slow resulting in performance degradatiion. I have used EntityFramework.Utilities for bulk insert into the database. I shall explain how to use Bulk insert in another post.