Tuesday, August 30, 2016

Server-side paging with ASP.NET Web API and Kendo UI Grids

If you need to implement a custom server-side paging solution with Kendo UI, it may not be readily obvious as to how to accomplish this!

Kendo UI has some code samples which partially addresses this scenario: https://github.com/telerik/ui-for-aspnet-mvc-examples/tree/master/grid/custom-ajax-binding/KendoGridCustomAjaxBinding

However, this example is tightly coupled to Entity Framework and does not work so well with ASP.NET Web API...

So how exactly can you adapt the Controller code sample to your own needs that work with ASP.NET Web API?

First of all, you need to make sure your Kendo Grid is setup as follows:
@(Html.Kendo().Grid<KendoGridCustomAjaxBinding.Models.Order>()
.Name("Grid")
.BindTo(Model)
.Columns(columns => {
columns.Bound(o => o.OrderID);
columns.Bound(o => o.ShipAddress);
})
.Pageable()
.Sortable()
.Scrollable()
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(true)
.PageSize(10)
.Read("Orders_Read", "Home")
)
)
Notice that you have to set ServerOperation(true)

Next, you have to set up your Controller code as follows:

using Kendo.Mvc;
using Kendo.Mvc.UI;
using KendoGridCustomAjaxBinding.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace KendoGridCustomAjaxBinding.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Orders_Read([DataSourceRequest]DataSourceRequest request)
{
var total = GetWebAPIRecordCount(); //Call Web API to get your total record count
var orders = GetPagedWebAPIRecords(request.PageSize, request.Page); //Call Web API to get your paged results
var result = new DataSourceResult()
{
Data = orders, // Process data (paging and sorting applied)
Total = total // Total number of records
};
return Json(result, JsonRequestBehavior.AllowGet);
}
}
}
That is all there is to it!

1 comment: