C#MVC2 Jqgrid – 服务器端分页的正确方法是什么?

我有一个jqgrid,其中数据库表有几千行,但jqrid一次只显示15。

它应该非常快速地显示(查询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()。Take()错了吗?
  • 我完全错过了其他的东西吗?

编辑

将我的代码与Oleg发布的示例进行比较时,我可以看到我按此顺序执行操作:

  1. 得到所有
  2. 选择模型字段

Wheras Olegs样本似乎按此顺序:

  1. 得到所有
  2. 选择模型字段

所以我改为这个更简单的实现:

 public ActionResult GetProductList(int page, int rows, string sidx, string sord, string searchOper, string searchField, string searchString) { List 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... 

我现在可以看到Oleg的样本的唯一区别是他的getAll返回IQueryable ,其中我的只是List

您应该发布更多完整代码。 例如,当前代码中未定义model.ToGridData 。 你如何从imput patrameters等中提取index也不清楚。 只有model.ToGridData()可以说明你的程序产生的输出是否与你定义的jsonReader相对应。

我建议你看看这个老答案,其中使用了分页和排序。 在另一个答案中,您将找到更多对代码示例的引用。