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

Datetime:2016-08-22 22:04:43          Topic: ASP.NET MVC           Share

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:

CREATE DATABASE Employee  
GO
USE Employee
GO
CREATE TABLE Employee  
  (  
  EmployeeID INT IDENTITY(1,1) CONSTRAINT Pk_Emp_Id PRIMARY KEY,  
  FirstName VARCHAR(20),  
  LastName VARCHAR(20)  
  )  

Insert some sample record, which is given below:

INSERT INTO Employee VALUES('Bob','Ross')  
INSERT INTO Employee VALUES('Pradeep','Raj')  
INSERT INTO Employee VALUES('Arun','Kumar')  
INSERT INTO Employee VALUES('Vasanth','Kumar')  

The table design is given below:

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.

Please refer to my previousarticleto 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.

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.

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

private EmployeeEntities db = new EmployeeEntities();  
      
         
         
       // GET: Employee  
      public ActionResult GetAllEmployee([DataSourceRequest]DataSourceRequest request)  
       {  
           try {   
  
           var employee = db.Employees.ToList();  
  
           return Json(employee.ToDataSourceResult(request));  
           }  
           catch(Exception ex)  
           {  
               return Json(ex.Message);  
           }  
  
       }  
       
       // UPDATE: Employee  
  
       public ActionResult UpdateEmployee([DataSourceRequest]DataSourceRequest request, Employee emp)  
       {  
           try  
           {  
               if (ModelState.IsValid)  
               {  
                   db.Entry(emp).State = EntityState.Modified;  
                   db.SaveChanges();  
                   return Json(new[] { emp}.ToDataSourceResult(request,ModelState));  
  
               }  
               else  
               {  
                   return Json(db.Employees.ToList());  
               }  
           }  
           catch(Exception ex)  
           {  
               return Json(ex.Message);  
           }  
       }  
  
       // ADD: Employee  
  
       public ActionResult AddEmployee([DataSourceRequest]DataSourceRequest request, Employee emp)  
       {  
           try {   
           if (ModelState.IsValid)  
           {  
  
               db.Employees.Add(emp);  
               db.SaveChanges();  
                   var _emplist = db.Employees.ToList();  
              return Json(new[] { emp}.ToDataSourceResult(request,ModelState));  
           }  
  
           else  
           {   
           return Json(db.Employees.ToList());  
           }  
           }  
           catch(Exception ex)  
           {  
               return Json(ex.Message);  
           }  
       }  
  
       // DELETE: Employee  
  
       public ActionResult DeleteEmployee([DataSourceRequest]DataSourceRequest request,Employee emp)  
       {  
           try  
           {   
           Employee employee = db.Employees.Find(emp.EmployeeID);  
           if (employee == null)  
           {  
               return Json("Employee Not Found");  
           }  
  
           db.Employees.Remove(employee);  
           db.SaveChanges();  
           return Json(db.Employees.ToList());  
           }  
           catch(Exception ex)  
           {  
               return Json(ex.Message);  
           }  
       }  
   }  

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,

@model KendoMvcApp.Models.Employee  
  
@{  
    ViewBag.Title = "EmployeeCRUD";  
      
}  
  
<h2>EmployeeCRUD</h2>  
  
<div class="container">  
    <div class="row">  
  
        @(Html.Kendo().Grid<KendoMvcApp.Models.Employee>()  
    .Name("EmpGrid")  
    .Selectable()  
    .Columns(columns =>  
    {  
      //  columns.Bound(c => c.EmployeeID);  
        columns.Bound(c => c.FirstName);  
        columns.Bound(c => c.LastName);  
        columns.Command(command =>  
        {  
            command.Edit();  
            command.Destroy();  
        }).Width(200);  
  
    })  
    .DataSource(dataSource => dataSource  
        .Ajax()  
        .Model(model=>  
        {  
            model.Id(emp => emp.EmployeeID);  
            model.Field(emp => emp.EmployeeID).Editable(false);  
        }  
        )  
        .Read(read => read.Action("GetAllEmployee", "EmployeesCRUD"))  
      .Update(update=>update.Action("UpdateEmployee", "EmployeesCRUD"))  
      .Create(create=>create.Action("AddEmployee","EmployeesCRUD"))  
      .Destroy(destroy=>destroy.Action("DeleteEmployee","EmployeesCRUD"))  
  
        )  
   .ToolBar(toolbar => toolbar.Create())  
  
   // Set grid editable.  
   .Editable(editable => editable.Mode(GridEditMode.InLine))  
  
    // Set grid sortable.  
    .Sortable()  
  
    // Set grid selectable.  
    .Selectable()  
  
    // Set grid pagable.  
    .Pageable(pageable =>  
    {  
        pageable.Refresh(true);  
        pageable.PageSizes(true);  
    })  
        )  
    </div>  
</div>  
Result

Run the project, go to EmployeesCRUD Controller and EmployeeCRUD Index View (ex: http://localhost/EmployeesCRUD/Index).

GET/READ

ADD/CREATE

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

Change in table is shown below:

UPDATE

Changes in the table are given below:

DELETE

Changes in the table are given below:

Source Code

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





About List