繁体   English   中英

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

[英]Can't make Datatables Pagination with Stored Procedure in MVC5

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

不仅显示此消息:

找不到记录可显示

而且,选择页面和页面大小选择器不会显示

正常: 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。这是错误的,它应该从表中获取总记录。 因此,您无需更改任何其他内容,只需编写新的存储过程即可获取记录计数。

控制器 :将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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM