CRUD In Kendo Grid Using ASP.NET MVC And Entity Framework

Introduction

In this article, I’ll describe, how to perform basic CRUD in Kendo grid, using ASP.NET.MVC and Entity Framework. The Application is developed basically, using Entity Framework database first approach and MVC. 

Prerequisites

Basic Knowledge in ASP.NET MVC, Entity Framework and Kendo UI framework.

Set up the Database

Open SSMS with new query Window, create a new database and a table for the demo purpose. Here, the script to create a database and table is given below:

  1. CREATE DATABASE Employee  
  2. GO
  3. USE Employee
  4. GO
  5. CREATE TABLE Employee  
  6.   (  
  7.   EmployeeID INT IDENTITY(1,1) CONSTRAINT Pk_Emp_Id PRIMARY KEY,  
  8.   FirstName VARCHAR(20),  
  9.   LastName VARCHAR(20)  
  10.   )  

Insert some sample record, which is given below:

  1. INSERT INTO Employee VALUES('Bob','Ross')  
  2. INSERT INTO Employee VALUES('Pradeep','Raj')  
  3. INSERT INTO Employee VALUES('Arun','Kumar')  
  4. INSERT INTO Employee VALUES('Vasanth','Kumar')  

The table design is given below:

 table

Create a new ASP.NET MVC application

Create a new empty ASP.NET MVC Application, as per the following figures. Open Visual Studio ->File ->New project ->ASP.NET Web Application. 

new
 
new

Please refer to my previous article to check out, how to configure Kendo UI in ASP.NET MVC Application. 

Generate the Model

Now, we will create Entity Framework models from the database tables.

Step 1: Right-click the Models folder, select Add and New Item.

Step 2: In the Add New Item Window, select data in the left pane and ADO.NET Entity Data Model from the center pane. Name the new model file Employee and Ccick Add.

Step 3: In the Entity Data Model Wizard, select EF Designer from the database and click Next.

EF Designer

Step 4: Click the New Connection button.

Step 5: In the Connection Properties Window, provide the name of the local Server, where the database was created (in this case (DESKTOP-585QGBN)). After providing the Server name, select the Employee from the available databases and click OK.

Properties

Step 6: You can use the default name for the connection to save in the Web.Config file and click Next.

Step 7: Select Table to generate models for Employee table and click Finish.

Create a Controller

Create a new empty controller. Right-click the Controllers folder and select Add –> New Empty Controller. In my case, I named it as EmployeeCRUD Controller

Write the code, given below, in the controller:

EmployeeCRUDController.cs 
  1. private EmployeeEntities db = new EmployeeEntities();  
  2.       
  3.          
  4.          
  5.        // GET: Employee  
  6.       public ActionResult GetAllEmployee([DataSourceRequest]DataSourceRequest request)  
  7.        {  
  8.            try {   
  9.   
  10.            var employee = db.Employees.ToList();  
  11.   
  12.            return Json(employee.ToDataSourceResult(request));  
  13.            }  
  14.            catch(Exception ex)  
  15.            {  
  16.                return Json(ex.Message);  
  17.            }  
  18.   
  19.        }  
  20.        
  21.        // UPDATE: Employee  
  22.   
  23.        public ActionResult UpdateEmployee([DataSourceRequest]DataSourceRequest request, Employee emp)  
  24.        {  
  25.            try  
  26.            {  
  27.                if (ModelState.IsValid)  
  28.                {  
  29.                    db.Entry(emp).State = EntityState.Modified;  
  30.                    db.SaveChanges();  
  31.                    return Json(new[] { emp}.ToDataSourceResult(request,ModelState));  
  32.   
  33.                }  
  34.                else  
  35.                {  
  36.                    return Json(db.Employees.ToList());  
  37.                }  
  38.            }  
  39.            catch(Exception ex)  
  40.            {  
  41.                return Json(ex.Message);  
  42.            }  
  43.        }  
  44.   
  45.        // ADD: Employee  
  46.   
  47.        public ActionResult AddEmployee([DataSourceRequest]DataSourceRequest request, Employee emp)  
  48.        {  
  49.            try {   
  50.            if (ModelState.IsValid)  
  51.            {  
  52.   
  53.                db.Employees.Add(emp);  
  54.                db.SaveChanges();  
  55.                    var _emplist = db.Employees.ToList();  
  56.               return Json(new[] { emp}.ToDataSourceResult(request,ModelState));  
  57.            }  
  58.   
  59.            else  
  60.            {   
  61.            return Json(db.Employees.ToList());  
  62.            }  
  63.            }  
  64.            catch(Exception ex)  
  65.            {  
  66.                return Json(ex.Message);  
  67.            }  
  68.        }  
  69.   
  70.        // DELETE: Employee  
  71.   
  72.        public ActionResult DeleteEmployee([DataSourceRequest]DataSourceRequest request,Employee emp)  
  73.        {  
  74.            try  
  75.            {   
  76.            Employee employee = db.Employees.Find(emp.EmployeeID);  
  77.            if (employee == null)  
  78.            {  
  79.                return Json("Employee Not Found");  
  80.            }  
  81.   
  82.            db.Employees.Remove(employee);  
  83.            db.SaveChanges();  
  84.            return Json(db.Employees.ToList());  
  85.            }  
  86.            catch(Exception ex)  
  87.            {  
  88.                return Json(ex.Message);  
  89.            }  
  90.        }  
  91.    }  

Create a View

Create a new empty controller, Right-click the EmployeeCRUD folder under View Folder, and select Add –>New Empty View. In my case, I named it as Index.cshtml.

Write the following code in Index.cshtml,
  1. @model KendoMvcApp.Models.Employee  
  2.   
  3. @{  
  4.     ViewBag.Title = "EmployeeCRUD";  
  5.       
  6. }  
  7.   
  8. <h2>EmployeeCRUD</h2>  
  9.   
  10. <div class="container">  
  11.     <div class="row">  
  12.   
  13.         @(Html.Kendo().Grid<KendoMvcApp.Models.Employee>()  
  14.     .Name("EmpGrid")  
  15.     .Selectable()  
  16.     .Columns(columns =>  
  17.     {  
  18.       //  columns.Bound(c => c.EmployeeID);  
  19.         columns.Bound(c => c.FirstName);  
  20.         columns.Bound(c => c.LastName);  
  21.         columns.Command(command =>  
  22.         {  
  23.             command.Edit();  
  24.             command.Destroy();  
  25.         }).Width(200);  
  26.   
  27.     })  
  28.     .DataSource(dataSource => dataSource  
  29.         .Ajax()  
  30.         .Model(model=>  
  31.         {  
  32.             model.Id(emp => emp.EmployeeID);  
  33.             model.Field(emp => emp.EmployeeID).Editable(false);  
  34.         }  
  35.         )  
  36.         .Read(read => read.Action("GetAllEmployee", "EmployeesCRUD"))  
  37.       .Update(update=>update.Action("UpdateEmployee", "EmployeesCRUD"))  
  38.       .Create(create=>create.Action("AddEmployee","EmployeesCRUD"))  
  39.       .Destroy(destroy=>destroy.Action("DeleteEmployee","EmployeesCRUD"))  
  40.   
  41.         )  
  42.    .ToolBar(toolbar => toolbar.Create())  
  43.   
  44.    // Set grid editable.  
  45.    .Editable(editable => editable.Mode(GridEditMode.InLine))  
  46.   
  47.     // Set grid sortable.  
  48.     .Sortable()  
  49.   
  50.     // Set grid selectable.  
  51.     .Selectable()  
  52.   
  53.     // Set grid pagable.  
  54.     .Pageable(pageable =>  
  55.     {  
  56.         pageable.Refresh(true);  
  57.         pageable.PageSizes(true);  
  58.     })  
  59.         )  
  60.     </div>  
  61. </div>  
Result
 
Run the project, go to EmployeesCRUD Controller and EmployeeCRUD Index View (ex: http://localhost/EmployeesCRUD/Index).
 
GET/READ

crud 
ADD/CREATE
 
Click Add new record button in toolbar of grid to add a new record in inline edit mode.

 ADD/CREATE
Change in table is shown below:

table

UPDATE

UPDATE 
Changes in the table are given below:

Table

DELETE

DELETE 

Changes in the table are given below:

Table

I hope you enjoyed this article. Your valuable feedback, questions or comments about this article are always welcome.

Up Next
    Ebook Download
    View all
    Learn
    View all