无法在 MVC5 中使用存储过程对数据表进行分页

Can't make Datatables Pagination with Stored Procedure in MVC5

我使用 DataTable 从 SQL 服务器加载数据并显示到 Table。 但它只是加载数据。 参考:https://gyazo.com/a77f5bee9c8f4fda3be8f9d130499bbf

不只显示这条消息:

No records found to show

而且,select 页面和页面大小 select 或者不显示

正常:https://gyazo.com/3f6d5193f36b756f752bdd20523d64e0

希望大家帮帮我。非常感谢

HTML:

<table class="table table-striped table-bordered table-hover table-checkable" id="datatable_products">
   <thead>
      <tr role="row" class="heading">
         <th width="1%">
            <input type="checkbox" class="group-checkable">
         </th>
         <th width="10%"> ID </th>
         <th width="15%"> Product&nbsp;Name </th>
         <th width="15%"> Category </th>
         <th width="10%"> Price </th>
         <th width="15%"> Promotion&nbsp;Price </th>
         <th width="10%"> Quantity </th>
         <th width="15%"> Date&nbsp;Created </th>
         <th width="10%"> Status </th>
         <th width="10%"> Actions </th>
      </tr>
   </thead>
   <tbody>
   </tbody>
</table>

SQL 存储过程:

USE [OnlineShop]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[LoadProduct]
    @Start     INT=0, 
    @PageLimit INT=10
AS
BEGIN
    SET NOCOUNT ON;
    SELECT p.ID, p.Name, c.Name Category, p.Price, p.PromotionPrice, (SELECT SUM(Quantity) FROM ProductSizeColor WHERE ProductID = p.ID) as 'SumQuantity', p.CreatedDate, p.[Status]
    FROM Product p
    LEFT JOIN ProductCategory c
    ON p.CategoryID = c.ID
    ORDER  BY ID
    OFFSET @Start ROW
    FETCH NEXT @PageLimit ROWS ONLY
END

Javascript:

 var handleProducts = function() {
    var grid = new Datatable();

    grid.init({
        src: $("#datatable_products"),
        onSuccess: function(grid) {
            // execute some code after table records loaded
        },
        onError: function(grid) {
            // execute some code on network or other general error  
        },
        loadingMessage: 'Loading...',
        dataTable: {
            "lengthMenu": [
                [10, 20, 50, 100, 150],
                [10, 20, 50, 100, 150] // change per page values here 
            ],
            "pageLength": 10, // default record count per page
            "ajax": {
                "url": "LoadProductTest", // ajax source
            },
            "processing": true,
            "serverSide": true,
            "columns": [
                          {"data": "ForCheckbox"}, 
                          {"data": "ID"}, 
                          {"data": "Name"}, 
                          {"data": "Category"}, 
                          {"data": "Price"}, 
                          {"data": "PromotionPrice"}, 
                          {"data": "SumQuantity"}, 
                          {"data": "CreatedDate"}, 
                          {"data": "DisplayStatus"}, 
                          {"data": "ForAction"},
            ],
            "order": [
                    [1, "asc"]
                ] // set first column as a default sort by asc
        }
    });

控制器:

public ActionResult LoadProductTest()
    {
        //
        var draw = Request.Form.GetValues("draw").FirstOrDefault();
        var start = Request.Form.GetValues("start").FirstOrDefault();
        var length = Request.Form.GetValues("length").FirstOrDefault();

        int pageSize = length != null ? Convert.ToInt32(length) : 0;
        int skip = start != null ? Convert.ToInt32(start) : 0;

        var model = new ProductDao().LoadProduct(skip, pageSize);

        int totalRecords = 0;
        return Json(new { draw = draw, recordsFiltered = totalRecords, recordsTotal = totalRecords, data = model } , JsonRequestBehavior.AllowGet);
    }

方法加载产品:

public List<ProductViewModel> LoadProduct(int start, int pageLimit)
    {
        object[] sqlParams = {
            new SqlParameter("@Start", start),
            new SqlParameter("@PageLimit", pageLimit)
        };
        return _db.Database.SqlQuery<ProductViewModel>("LoadProduct @Start, @PageLimit", sqlParams).ToList();
    }

我找到了解决这个问题的方法。 在控制器中,我设置了 totalRecords = 0。这是错误的,它应该从 table 中获取总记录。 因此,您无需更改任何其他内容,只需编写新的存储过程即可获取记录数。

Controller : 将 totalRecords = 0 更改为

int totalRecords = new ProductDao().CountProduct();

CountProduct 函数:

public int CountProduct()
    {
        return _db.Database.SqlQuery<int>("CountProduct").SingleOrDefault();
    }

统计记录的存储过程:

CREATE PROCEDURE CountProduct
AS
BEGIN
    SELECT COUNT(*) FROM Product 
END
GO