Telerik Grid Custom Binding

Telerik Grid算是做得很完善,API也多~但客製化需求還是在所難免。
比如有個表單系統只提供最簡單的資料瀏覽,姑且不論是否下查詢條件,要是資料百萬筆豈不是起肖?!

較好的做法是用分頁區別之餘,但每次只取該分頁的資料,而不是一次取回百萬筆資料再作分頁

本文就要來介紹,如何實作Custom Binding

1. 計算總筆數(因為是CustomBinding,GridModel需要的總筆數必須自己計算)
public int QueryPOListIndex(GridCommand command)
{
var entity = mydata.PO.AsQueryable();
int ttlCount = entity.ToList().Count();
return ttlCount;
}


2. 像平常一樣取資料(請依照自己的需求和資料作變化)
public List<PO> QueryPOList(GridCommand command)
{
var entity = mydata.PO.AsQueryable();
//Sorting(必須有Default的Order By條件,否則會Error)
entity = entity.OrderBy(order => order.PONo);
//Then paging
if (command.PageSize > 0)
entity = entity.Skip((command.Page - 1) * command.PageSize);
entity = entity.Take(command.PageSize);
return entity.ToList();
}


前面二項為Bussiness Layer(POService),若專案架構較小~亦可將其寫在Controller中
3. Controller
//須注意的是, ViewBag.DataTotalCount在此頁載入時須先給予一預設值(ex:0),之後的查詢function再賦予正確值
public ActionResult ListPO()
{
ViewBag.POTotalCount = 0;
return View();
}

[GridAction(EnableCustomBinding = true)]
public ActionResult ListPO_CustomBinding(GridCommand command)
{
int totalCount = POService.QueryPOListIndex(command);
ViewBag.POTotalCount = totalCount;
List<POt> data = POService.QueryPOList(command);
return View(new GridModel
{
Data = data,
Total = totalCount
});
}


4. View
@(Html.Telerik().Grid<PO>()
.Name("Grid")
.Columns(columns => {
columns.Bound(c => c.PONo);
columns.Bound(c => c.DocDate);
columns.Bound(c => c.Company);
columns.Bound(c => c.Vendor);
columns.Bound(c => c.Status);
columns.Bound(c => c.CmpltReceived);
})
.Pageable(settings => settings.Total((int)ViewBag.POTotalCount))
.DataBinding(dataBinding => dataBinding.Ajax().Select("ListPO_CustomBinding", "Inbound"))
.EnableCustomBinding(true)

.Sortable()
.Groupable()
)

沒有留言: