CRUD In Kendo Gird Using AngularJS And ASP.NET WEB API

This article will show you how to get the Kendo UI support to work with CRUD operations in grid using AngularJS.

This article flow as follows,

  1. Creating an ASP.NET Web API application.
  2. Creating a Controller.
  3. Implementing the CRUD operation in Kendo Grid using AngularJS with the REST API.

Create a Web API application using an installed web template in Visual Studio as in the following figures:

 
 
 
 

Creating a Model Classes:

In the Solution Explorer, right click the model folder, Add-> Class and name it as Department

Department.cs

  1. public class Department  
  2.     {  
  3.         public int? DepartmentID { getset; }  
  4.         [Required]  
  5.         public string DepartmentName { getset; }  
  6.     }  

Creating a Context Class:

Add one more class in the Model and name it DetailGridContext which is our Entity framework code first context.

DetailGridContext.cs

  1. public class DetailGridContext : DbContext  
  2.     {  
  3.       
  4.         public DetailGridContext() : base("name=DetailGridContext")  
  5.         {  
  6.         }  
  7.   
  8.         public System.Data.Entity.DbSet<DetailGrid.Models.Department> Departments { getset; }  
  9.     }  
Seed the Database:

Now, open the Package manager console and run the following commands,

1.Enable-migrations
 
This will add the folder called migration with code file named configuration.cs
 
2.Add-Migration Initial

Check your Web config file and ensure the SQL connection string,

Open configuration.cs file under migration folder and add the following code in seed method,

Configuration.cs

  1. protected override void Seed(DetailGrid.Models.DetailGridContext context) {  
  2.   
  3. context.Departments.AddOrUpdate(new Department { DepartmentID = 4, DepartmentName = "Development" },  
  4.          new Department { DepartmentID = 5, DepartmentName = "Testing" },   
  5. new Department { DepartmentID = 6, DepartmentName = "Infrastructure" });    }  

3. Update-Database

This will run the seed method,

Check you database which is created 
 
 
 
 Department Table  
 
  

Please refer to my previous ASP.NET Web API With Entity Framework 6 Code First Technique - Part 1 to get more detail about Entity Framework code first technique.

Creating WEB API Controller:

Note: Before adding the controller build your application once.

In Solution Explorer, right-click the Controller folder. Select Add -> Controller and name it DepartmentsController.cs

 

DepartmentController.cs
  1. public class DepartmentsController : ApiController

  2. {  

  3.     private DetailGridContext db = new DetailGridContext();  
  4.   
  5.     // GET: api/Departments  
  6.     public IQueryable<Department> GetDepartments()  
  7.     {  
  8.         return db.Departments;  
  9.     }  
  10.   
  11.     // GET: api/Departments/5  
  12.     [ResponseType(typeof(Department))]  
  13.     public async Task<IHttpActionResult> GetDepartment(int id)  
  14.     {  
  15.         Department department = await db.Departments.FindAsync(id);  
  16.         if (department == null)  
  17.         {  
  18.             return NotFound();  
  19.         }  
  20.   
  21.         return Ok(department);  
  22.     }  
  23.   
  24.     // PUT: api/Departments/5  
  25.     [ResponseType(typeof(void))]  
  26.     public async Task<IHttpActionResult> PutDepartment(Department department)  
  27.     {  
  28.         if (!ModelState.IsValid)  
  29.         {  
  30.             return BadRequest(ModelState);  
  31.         }  
  32.           
  33.   
  34.         db.Entry(department).State = EntityState.Modified;  
  35.   
  36.         try  
  37.         {  
  38.             await db.SaveChangesAsync();  
  39.         }  
  40.         catch (DbUpdateConcurrencyException)  
  41.         {  
  42.             if (!department.DepartmentID.HasValue)  
  43.             {  
  44.                 return NotFound();  
  45.             }  
  46.             else  
  47.             {  
  48.                 throw;  
  49.             }  
  50.         }  
  51.   
  52.         return StatusCode(HttpStatusCode.NoContent);  
  53.     }  
  54.   
  55.     // POST: api/Departments  
  56.     [ResponseType(typeof(Department))]  
  57.     public async Task<IHttpActionResult> PostDepartment(Department department)  
  58.     {  
  59.         if (!ModelState.IsValid)  
  60.         {  
  61.             return BadRequest(ModelState);  
  62.         }  
  63.   
  64.         db.Departments.Add(department);  
  65.         await db.SaveChangesAsync();  
  66.   
  67.         return CreatedAtRoute("DefaultApi"new { id = department.DepartmentID }, department);  
  68.     }  
  69.   
  70.     // DELETE: api/Departments/5  
  71.     [ResponseType(typeof(Department))]  
  72.     public async Task<IHttpActionResult> DeleteDepartment(Department _dept)  
  73.     {  
  74.         Department department = await db.Departments.FindAsync(_dept.DepartmentID);  
  75.         if (department == null)  
  76.         {  
  77.             return NotFound();  
  78.         }  
  79.   
  80.         db.Departments.Remove(department);  
  81.         await db.SaveChangesAsync();  
  82.   
  83.         return Ok(department);  
  84.     }  
  85.   
  86.     protected override void Dispose(bool disposing)  
  87.     {  
  88.         if (disposing)  
  89.         {  
  90.             db.Dispose();  
  91.         }  
  92.         base.Dispose(disposing);  
  93.     }  
  94.   
  95.     private bool DepartmentExists(int id)  
  96.     {  
  97.         return db.Departments.Count(e => e.DepartmentID == id) > 0;  
  98.     }  
  99. }  
Implementing the CRUD in Kendo Grid using AngularJS and the REST API

Creating a HTML page

Create a new HTML page in the project.

Design:

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8">  
  5.     <title>Untitled</title>  
  6.   
  7.     <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.1.412/styles/kendo.common.min.css">  
  8.     <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.1.412/styles/kendo.rtl.min.css">  
  9.     <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.1.412/styles/kendo.default.min.css">  
  10.     <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.1.412/styles/kendo.mobile.all.min.css">  
  11.   
  12.     <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>  
  13.     <script src="http://kendo.cdn.telerik.com/2016.1.412/js/angular.min.js"></script>  
  14.     <script src="http://kendo.cdn.telerik.com/2016.1.412/js/jszip.min.js"></script>  
  15.     <script src="http://kendo.cdn.telerik.com/2016.1.412/js/kendo.all.min.js"></script>  
  16. </head>  
  17. <body>  
  18.     <div id="example" ng-app="KendoDemos">  
  19.         <h3 style="font-style:italic;color:#F35800">CRUD in Kendo Gird using AngularJS and ASP.NET WEB API </h3>  
  20.         <br />  
  21.          
  22.         <div ng-controller="MyCtrl">  
  23.             <kendo-grid k-options="mainGridOptions">  
  24.               
  25.             </kendo-grid>  
  26.   
  27.   
  28.         </div>  
  29.     </div>  
  30.   
  31.     <script>  
  32.     angular.module("KendoDemos", [ "kendo.directives" ])  
  33.         .controller("MyCtrl"function ($scope) {  
  34.   
  35.             $scope.mainGridOptions = {  
  36.                 
  37.                     dataSource: {  
  38.                         type: "json",  
  39.                         transport: {  
  40.                             read:  
  41.              {  
  42.                  url: "api/Departments",  
  43.                  dataType: "json",  
  44.              },  
  45.                             destroy:  
  46.              {  
  47.                  url: "api/Departments",  
  48.                  type: "DELETE"  
  49.              },  
  50.                             create:  
  51.                             {  
  52.                                 url: "api/Departments",  
  53.                                 type: "POST"  
  54.                             },  
  55.                             update:  
  56.                             {  
  57.                                 url: "api/Departments" ,  
  58.                                 type: "PUT",  
  59.                               
  60.                             parameterMap: function (options, operation) {  
  61.                                 if (operation !== "read" && options.models) {  
  62.                                     return {  
  63.                                         models: kendo.stringify(options.models)  
  64.                                     };  
  65.                                 }  
  66.                             }  
  67.                             },  
  68.   
  69.   
  70.                         },  
  71.                         schema:  
  72.          {  
  73.              model:  
  74.              {  
  75.                  id: "DepartmentID",  
  76.                  fields: {  
  77.                      DepartmentID: { editable: false, nullable: true, type: "number" },  
  78.                      DepartmentName: { editable: true, nullable: true, type: "string" },  
  79.                  }  
  80.              }  
  81.          },  
  82.                         pageSize: 5,  
  83.                         serverPaging: true,  
  84.                         serverSorting: true  
  85.                     },  
  86.   
  87.                     editable: "inline",  
  88.                     toolbar: ["create"],  
  89.                     sortable: true,  
  90.                     pageable: true,  
  91.                     resizeable: true,  
  92.                     columns: [{  
  93.                         field: "DepartmentID",  
  94.                         title: "DepartmentID",  
  95.                         width: "180px"  
  96.                     }, {  
  97.                         field: "DepartmentName",  
  98.                         title: "Department Name",  
  99.                         width: "180px"  
  100.                     },  
  101.                         {  
  102.                             command: ["edit",  
  103.                             {  
  104.                                 name: "destroy",  
  105.                                 text: "remove",  
  106.                                 width: "120px"  
  107.                             }  
  108.                             ],  
  109.                         }  
  110.                     ]  
  111.                 };  
  112.              
  113.   
  114.               
  115.         })  
  116.     </script>  
  117. </body></html>  

Read operation

Initially when the page loads the read property in datasource of grid will invoke which used to render table rows

  1. read:  
  2. {  
  3.     url: "api/Departments",  
  4.     dataType: "json",  
  5. },  
Result
 
  
Create Operation

The toolbar property is used to implement the add a record button in grid which is responsible to perform the create operation by invoking the POST API.

  1. toolbar: ["create"],//add create button in grid  
  1. create:  
  2. {  
  3.     url: "api/Departments",  
  4.     type: "POST"  
  5. },  

The above create property in datasource of grid is used to invoke the POST API

Result:
 
  
Update Operation

The command property is used to implement the Edit button in grid which is responsible to perform the update operation by invoking the PUT API.

  1.                         command: ["edit",  
  2.                             {  
  3.                                 width: "120px"  
  4.                             }  
  5.                             ],  
  1.                        update:  
  2.                             {  
  3.                                 url: "api/Departments" ,  
  4.                                 type: "PUT",  
  5.                         
  6.                              }  

The above update property in datasource of grid is used to invoke the PUT API.

 

Delete Operation

The command property is used to implement the remove button in grid which is responsible to perform the delete operation by invoking the DELETE API.

  1. command: [  
  2.                             {  
  3.                                 name: "destroy",  
  4.                                 text: "remove",  
  5.                                 width: "120px"  
  6.                             }     
  7.                             ],  
  8.          
  1.                   destroy:  
  2.                  {
  3.                   url: "api/Departments",  
  4.                    type: "DELETE"  
  5.                   },  
The above destroy property in datasource of grid is used to invoke the DELETE API.
 

Conclusion

We have seen how to perform CRUD operations in Kendo grid using AngularJS, which is really useful to build a complex application with ease. I hope you have enjoyed this article. Your valuable feedback, questions, or comments about this article are always welcomed.

Read more article on AngularJS:


Similar Articles