Server Side Paging In Kendo Grid For Angular 2 Using ASP.NET Web API

Introduction

This article explains how to perform Server-side paging of Kendo Grid for Angular 2, using ASP.NET Web API. To explain it, I have created a RESTful get Service, using ASP.NET Web API, which is used to load the data source of Kendo Grid for Angular 2.

Prerequisites

Basic knowledge of ASP.NET Web API, Kendo UI, and Angular 2 framework.

This article flows as follows,

  1. Creating an ASP.NET Web API Application.
  2. Creating a Controller.
  3. Testing the REST API.
  4. Creating a Kendo UI for Angular 2 Application.
  5. Implementing the server side paging in Kendo Grid for Angular 2.

Creating an ASP.NET WEB API Application:

Create a Web API application, using an installed Web template in Visual Studio, as shown below. In my case, I named the application "EmployeeAPI"



 
Creating model classes

In the Solution Explorer, right click the Models folder, select Add followed by Class, and name it Employee.cs.

  1. public class Employee  
  2.   {  
  3.       public Employee(int Id, string Name, string Designation)  
  4.       {  
  5.           this.EmployeeID = Id;  
  6.           this.EmployeeName = Name;  
  7.           this.Designation = Designation;  
  8.   
  9.       }  
  10.       public int EmployeeID { get; set; }  
  11.       public string EmployeeName { get; set; }  
  12.       public string Designation { get; set; }  
  13.   }  

Creating a Controller

Right click on the Controller folder and add a new Web API 2- Empty controller, as shown in figure 3. In my case, I named it as EmployeeController.cs.

 
 
EmployeeController.cs
  1. [RoutePrefix("api/Employee")]  
  2.     public class EmployeeController : ApiController  
  3.     {  
  4.         [HttpGet]  
  5.         [AllowAnonymous]  
  6.         [Route("EmployeeList")]  
  7.         public HttpResponseMessage GetEmployee(string Skip,string Take)  
  8.         {  
  9.             try  
  10.             {  
  11.                 List<Employee> EmpLists = new List<Employee>();  
  12.                 EmpLists.Add(new Employee(1, "Govind Raj""Business Analyst"));  
  13.                 EmpLists.Add(new Employee(2, "Krishn Mahato""Development"));  
  14.                 EmpLists.Add(new Employee(3, "Bob Ross""Testing"));  
  15.                 EmpLists.Add(new Employee(4, "Steve Davis""Development"));  
  16.                 EmpLists.Add(new Employee(5, "Dave Tucker""Infrastructure"));  
  17.                 EmpLists.Add(new Employee(6, "James Anderson""HR"));  
  18.                 var data = EmpLists.Skip(Convert.ToInt32(Skip)).Take(Convert.ToInt32(Take));  
  19.                 int count = EmpLists.Count;  
  20.                 return Request.CreateResponse(HttpStatusCode.OK, new { Count=count, EmployeeList=data }, Configuration.Formatters.JsonFormatter);  
  21.             }  
  22.             catch (Exception ex)  
  23.             {  
  24.                 return Request.CreateResponse(HttpStatusCode.OK, ex.Message, Configuration.Formatters.JsonFormatter);  
  25.             }  
  26.         }  
  27.     }  

The Employee Controller Action GetEmployee will return a list of employees.

Testing the REST API

Test API, using the POSTMAN/Fiddler, as shown in figure 4.

  • API End Point /api/Employee/EmployeeListt?Skip=0&Take=5.
  • Type GET.

 
Creating a Kendo UI for Angular 2 Application

Please go through my previous article to get to know how to create and configure Kendo UI for Angular 2.

Implementing the DataBinding in Kendo Grid for Angular 2

In my previous article, we have seen how to configure Kendo Grid for Angular 2. Now, we are going to use the same configuration but the change is the Grid DataSource, which is populated from RESTtful Service response with Server side paging.

Write the code, mentioned below, in src/app/app.module.ts.

  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { FormsModule } from '@angular/forms';  
  4. import { GridModule } from '@progress/kendo-angular-grid';  
  5. import { HttpModule } from '@angular/http';  
  6. import { AppComponent } from './app.component';  
  7.   
  8.   
  9. @NgModule({  
  10.     declarations: [  
  11.         AppComponent],  
  12.     imports: [  
  13.         BrowserModule,  
  14.         FormsModule,  
  15.         HttpModule,  
  16.         GridModule,  
  17.     ],  
  18.     providers: [],  
  19.     bootstrap: [AppComponent]  
  20. })  
  21. export class AppModule { }  

Write the code, mentioned below, in app.component.ts.

  1. import { Component, ViewChild, Input, OnInit, Injectable } from '@angular/core';  
  2. import { Http } from '@angular/http';  
  3. import { URLSearchParams, QueryEncoder } from '@angular/http';  
  4. import { Observable, BehaviorSubject } from 'rxjs/Rx';  
  5.   
  6. import {  
  7.     GridComponent,  
  8.     GridDataResult,  
  9.     DataStateChangeEvent  
  10. } from '@progress/kendo-angular-grid';  
  11.   
  12.   
  13. /* Example service */  
  14. @Injectable()  
  15. export class EmployeeService extends BehaviorSubject<GridDataResult> {  
  16.     private BASE_URL: string = 'http://localhost:1237/api/Employee/EmployeeList';  
  17.       
  18.     constructor(private http: Http) {  
  19.         super(null);  
  20.     }  
  21.   
  22.     public query(state): void {  
  23.         this.getEmployee(state)  
  24.             .subscribe(x =>super.next(x));  
  25.     }  
  26.   
  27.   
  28.     private getEmployee(state: any): Observable<GridDataResult>{  
  29.         let params = new URLSearchParams();  
  30.         params.set('Skip', state.skip);  
  31.         params.set('Take', state.take)  
  32.         return this.http  
  33.             .get(this.BASE_URL, { search: params })  
  34.             .map(response => response.json())  
  35.             .map(response => (<GridDataResult>{  
  36.                 data: response.EmployeeList,  
  37.                 total: response.Count  
  38.             }));  
  39.           
  40.     }  
  41.       
  42. }  
  43.   
  44. @Component({  
  45.     providers: [EmployeeService],  
  46.     selector: 'app-root',  
  47.     template: `  
  48.       <kendo-grid  
  49.           [data]="view | async"  
  50.           [pageSize]="pageSize"  
  51.           [skip]="skip"  
  52.           [pageable]="true"  
  53.         >  
  54.         <kendo-grid-column field="EmployeeID" width="200"></kendo-grid-column>  
  55.         <kendo-grid-column field="EmployeeName" width="200"></kendo-grid-column>  
  56.         <kendo-grid-column field="Designation"  width="500" [sortable]="false">  
  57.         </kendo-grid-column>  
  58.       </kendo-grid>  
  59.   `  
  60. })  
  61.   
  62. export class AppComponent {  
  63.     private view: Observable<GridDataResult>;  
  64.     private pageSize: number = 5;  
  65.     private skip: number = 0;  
  66.   
  67.     @ViewChild(GridComponent) private grid: GridComponent;  
  68.     constructor(private service: EmployeeService) {  
  69.         this.view = service;  
  70.         this.service.query({ skip: this.skip, take: this.pageSize });  
  71.     }  
  72.     public ngAfterViewInit(): void {  
  73.         this.grid.dataStateChange  
  74.             .do(({ skip, take }: DataStateChangeEvent) => {  
  75.                 this.skip = skip;  
  76.                 this.pageSize = take;  
  77.             })  
  78.             .subscribe(x => this.service.query(x));  
  79.     }  
  80.    
  81.   
  82. }  

From the code, mentioned above, it is obvious that Kendo Grid accesses RESTful GET Service to load its DataSource. Pageable, pageSize and skip option of the Grid is used to enable the paging.

Write the code, mentioned below, in Index.html. 
  1. <!doctype html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8">  
  5.     <title>KendoAngular</title>  
  6.     <base href="/">  
  7.   
  8.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  9.     <link rel="icon" type="image/x-icon" href="favicon.ico">  
  10. </head>  
  11. <body>  
  12.       
  13.     <app-root>Loading...  
  14.           
  15.     </app-root>  
  16. </body>  
  17. </html>  
Build and run the application by passing the command ng-server. 

The request sends to the Server when the page loads, as we initialized the value of skip and take which will be 0 and 5 respectively to load the first page

Result 
 
 
 
Kendo grid with paging in Browser
 


Click on 2 in grid pager which shown in figure 6  to load the second page
 




Conclusion

We have seen how to implement the server side paging in Kendo Grid for Angular 2, using ASP.NET WEB API. You will learn more about sorting, scroll, and selection of Kendo Grid for Angular 2 in my future articles. I hope you have enjoyed this article. Your valuable feedback, questions or comments about this article are always welcome.

References
  1. http://www.telerik.com/kendo-angular-ui/components/grid/q
  2. http://www.telerik.com/kendo-angular-ui/components/grid/data-binding/

Get the source code from GitHub.

Up Next
    Ebook Download
    View all
    Learn
    View all