我有一個jqgrid,其中數據庫表有幾千行,但jqrid一次只顯示15個。C#MVC2 Jqgrid - 做服務器端分頁的正確方法是什麼?
它應該很快顯示(查詢15行並不需要很長時間)。但相反,它需要10 - 20秒,這表明它每次都檢索整個表格。
網格的定義如下:
$("#Products").jqGrid({
url: url, mtype: "get", datatype: "json", jsonReader: {
root: "Rows", page: "Page", total: "Total", records: "Records", repeatitems: false,
userdata: "UserData",id: "Id"},
colNames: ["Product Id","Product Code", ... etc ],
colModel: [{ name: "Id", ... etc}],
viewrecords: true, height: 400, width: 800, pager: $("#jqgPager"),
rowNum: 15, rowList: [50, 100, 200],
autowidth: true, multiselect: false
並且服務器側(MVC2動作)執行此操作:
var model = (from p in products
select new
{
p.Id, p.ProductCode, p.ProductDescription,
AllocatedQty = p.WarehouseProducts.Sum(wp => wp.AllocatedQuantity),
QtyOnHand = p.WarehouseProducts.Sum(wp => wp.OnHandQuantity)
}).AsQueryable();
JsonResult json = Json(model.ToGridData(
page, rows, orderBy, "",
new[] { "Id", "ProductCode", "ProductDescription", "AllocatedQty", "QtyOnHand" }),
JsonRequestBehavior.AllowGet);
最後的model.ToGridData擴展方法執行此:
var data =_service.GetAll();
var page = data.Skip((index) * pageSize).Take(pageSize);
list.Add(page.AsEnumerable);
而且我對有問題的地方有點遺憾:
- 我是否錯誤地設置了jqgrid分頁選項?
- 我寫了不好的LINQ,不管拉什麼行?例如Sum()會導致所有行被讀取?
- 我已經完成了.Skip()。拿()不正確?
- 我完全錯過了其他的東西嗎?
編輯
當比較我的代碼張貼奧列格的例子,我可以看到我做的事情按以下順序:
- GETALL
- 選擇模型領域
- 頁
Wheras Olegs樣本似乎是在這orde R:
- GETALL
- 頁
- 選擇模型領域
所以我改變了這個更簡單的實現:
public ActionResult GetProductList(int page, int rows, string sidx, string sord,
string searchOper, string searchField, string searchString)
{
List<Product> products = _productService.GetAllProducts();
int totalRecords = products.Count();
var pagedData = products.Skip((page > 0 ? page - 1 : 0) * rows).Take(rows);
var model = (from p in pagedData
select new
{
p.Id, p.ProductCode, p.ProductDescription,
Barcode = string.Empty, UnitOfMeasure = string.Empty,
p.PackSize, AllocatedQty = string.Empty,
QtyOnHand = string.Empty }).ToList();
var jsonData = new
{
total = page, records = totalRecords,
page = (totalRecords + rows - 1)/rows, rows = model
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
但是,這有一個新的問題:
A circular reference was detected while serializing an object of type
'System.Data.Entity.DynamicProxies.Product_FA935D3899E2...
我現在可以看到的與奧列格的例子唯一的區別是,他的getAll返回IQueryable
其中我的只是List
。
謝謝,我已經根據第一個例子編輯我的問題。順便說一句,在'var jsonData ='語句中'total ='重複了兩次。 – 2010-11-17 22:24:37
@JK:可能你應該使用'var jsonData = new {...,rows = model};'而不是'var jsonData = new {...,rows = pagedData};'?目前你不使用你只分配的'model'變量。如果它沒有解決你的問題,你應該寫在你收到異常的哪一行。 – Oleg 2010-11-17 22:38:45
當然是的,我的錯誤......'rows = model'就是我想要的。它現在返回數據,我需要檢查它是否正常工作,並做一些時間測試等。 – 2010-11-17 23:04:58