JQuery的数据表服务器端分页 [英] JQuery DataTables server-side pagination

查看:164
本文介绍了JQuery的数据表服务器端分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的web应用程序我使用jQuery 数据表插件显示从数据库中检索数据。

我目前使用的客户端分页,但在我的表中的数据会成长很多,和装载在ASP.NET页面正在成为一个有点慢。所以我打算切换到服务器端分页。

我知道,数据表插件支持,但搜索周围我还没有找到明确无一不对实施它。

我的主要疑问是:如果我实现服务器端分页,我也必须执行顺序,或者我可以委托给客户端

你有没有经历过这样?

注意我使用LINQ to SQL连接到我的数据库


解决方案

现有的答案的可能的适用于旧版本的DataTable的,但目前的版本(我用1.10+)传递开始记录和长度所以任何提示帮您做生意* pageSize的是要给不正确的结果。

第一个简单的手工的方式

接受的答案也是为我想这样做很复杂,一些调试后,我发现,页面大小,并开始记录为HTTP 是简单地传递请求值名为启动长度。文本搜索如搜索[值] 的排序顺序是在一个名为元件通过为了[0] [专栏] 和排序方向为了[0] [DIR] 等。

基本code我曾经进行排序和筛选看起来是这样的:

获取分页,排序,并从HTTP Request对象的过滤值:

  INT STARTREC = 0;
int.TryParse(请求[开始],出STARTREC);
INT的pageSize = 10;
int.TryParse(请求[长度],出来的pageSize);
VAR搜索=请求[搜索[数值]];
VAR为了=请求[为了[0] [专栏]];
VAR方向=请求[为了[0] [DIR]];变种查询= this._dataStore.Records.AsQueryable();

应用(不区分大小写)首先搜索:

 如果(!string.IsNullOrWhiteSpace(搜索))
{
    查询= query.Where(X =方式> x.Label.ToLower()包含(search.ToLower()));
}

然后应用任何排序:

 开关(顺序)
{
    //我的id列
    情况下为0:
        查询=(方向==降序)? query.OrderByDescending(X => x.Id):query.OrderBy(X => x.Id);
        打破;
    //我的标签栏
    情况1:
        查询=(方向==降序)? query.OrderByDescending(X => x.Label):query.OrderBy(X => x.Label);
        打破;
}

最后应用分页:

 查询= query.Skip(STARTREC)。取(pageSize的);

正确的记录,现在正准备返回。

更新(使用Datatables.net为MVC5)

在我的理解服务器端数据表的基本知识,现在是时候开始寻找现有的插件/ utils的简化这个code。最合适的,到目前为止,我发现,对于MVC 5,是 Datatables.net为MVC5 的NuGet包


  1. 安装的NuGet包


  2. 改变控制器操作使用 DataTablesBinder 来提供IDataTablesRequest接口


例如

 公共JsonResult表([ModelBinder的(typeof运算(DataTablesBinder))] IDataTablesRequest requestmodel)

<醇开始=3>

  • 先涂上任何搜索过滤器:

  • 例如

     如果(!string.IsNullOrEmpty(requestmodel.Search.Value))
    {
        查询= query.Where(X =&GT; x.CompanyTypeName.Contains(requestmodel.Search.Value)|| x.CompanyTypeDescription.Contains(requestmodel.Search.Value));
    }

    <醇开始=4>

  • 的应用任何排序:

  • 例如

     的foreach(在requestmodel.Columns.GetSortedColumns VAR排序())
    {
        开关(sort.Name)
        {
            案CompanyTypeDescription:
                查询= sort.SortDirection == Column.OrderDirection.Ascendant? query.OrderBy(X =&GT; x.CompanyTypeDescription):query.OrderByDescending(X =&GT; x.CompanyTypeDescription);
                打破;
            案CompanyTypeName:
            默认:
                查询= sort.SortDirection == Column.OrderDirection.Ascendant? query.OrderBy(X =&GT; x.CompanyTypeName):query.OrderByDescending(X =&GT; x.CompanyTypeName);
                打破;
        }
    }


  • 然后使用应用分页跳过和以前一样:

  • 例如

      VAR的结果= query.Skip(requestmodel.Start)。取(requestmodel.Length)。选择(X =&gt;新建{x.CompanyTypeName,x.CompanyTypeDescription});

    <醇开始=6>

  • 最后返回使用 DataTablesResponse 对象JSON结果:

  • 例如

     返回JSON(新DataTablesResponse(requestmodel.Draw,结果,query.Count(),base.RefSureContext.CompanyType.Count()),JsonRequestBehavior.AllowGet);

    这简化了所有的搜索,排序和放大器;分页到一个很好的易于重复模式。

    对于插件的文档这里

    In my web-app I'm using JQuery DataTables plug-in to show data retrieved from database.

    I'm currently using client-side pagination, but data in my tables are growing a lot, and loading in ASP.NET pages is now becoming a bit slow. So I was planning to switch to server-side pagination.

    I know that DataTables plug-in supports it, but searching around I haven't found notting clear about implementing it.

    My main doubt is: if I implement pagination on server-side I also have to implement ordering, or I can delegate it to client-side?

    Have you ever experienced this?

    NOTE I'm using Linq to SQL to connect to my DB

    解决方案

    The existing answers might apply to an old version of dataTable, but current versions (I am using 1.10+) pass the start record and length so anything suggesting pageNo * pageSize is going to give incorrect results.

    First simple "manual" approach

    The accepted answer was also very complicated for what I wanted to do so, after some debugging, I found that the page size and start record are simply passed as Http Request values named start and length. The text search is passed as search[value] The sort order is passed in a member named order[0][column] and the sort direction in order[0][dir] etc.

    The basic code I used to sort and filter looks like this:

    Get the paging, sorting and filtering values from the HTTP Request object:

    int startRec = 0;
    int.TryParse(Request["start"], out startRec);
    int pageSize = 10;
    int.TryParse(Request["length"], out pageSize);
    var search = Request["search[value]"];
    var order = Request["order[0][column]"];
    var direction = Request["order[0][dir]"];
    
    var query = this._dataStore.Records.AsQueryable();
    

    Apply (case insensitive) search first:

    if (!string.IsNullOrWhiteSpace(search))
    {
        query = query.Where(x => x.Label.ToLower().Contains(search.ToLower()));
    }
    

    Then apply any sorting:

    switch (order)
    {
        // My id column
        case "0":
            query = (direction == "desc") ? query.OrderByDescending(x => x.Id) : query.OrderBy(x => x.Id);
            break;
        // My label column
        case "1":
            query = (direction == "desc") ? query.OrderByDescending(x => x.Label) : query.OrderBy(x => x.Label);
            break;
    }
    

    Finally apply the paging:

    query = query.Skip(startRec).Take(pageSize);
    

    The correct records are now ready to return.

    Update (using "Datatables.net for MVC5")

    Once I understood the basics of server-side dataTables, it was time to start looking for existing plugins/utils to simplify this code. The most appropriate one I have found so far, for MVC 5, is the Datatables.net for MVC5 nuget package.

    1. Install the NuGet Package

    2. Change the controller Action to use a DataTablesBinder to provide a IDataTablesRequest interface

    e.g.

     public JsonResult Table([ModelBinder(typeof(DataTablesBinder))] IDataTablesRequest requestmodel)
    

    1. Apply any search filter first:

    e.g.

    if (!string.IsNullOrEmpty(requestmodel.Search.Value))
    {
        query = query.Where(x => x.CompanyTypeName.Contains(requestmodel.Search.Value) || x.CompanyTypeDescription.Contains(requestmodel.Search.Value));
    }
    

    1. The apply any sorting:

    e.g.

    foreach (var sort in requestmodel.Columns.GetSortedColumns())
    {
        switch (sort.Name)
        {
            case "CompanyTypeDescription":
                query = sort.SortDirection == Column.OrderDirection.Ascendant ? query.OrderBy(x => x.CompanyTypeDescription) : query.OrderByDescending(x => x.CompanyTypeDescription);
                break;
            case "CompanyTypeName":
            default:
                query = sort.SortDirection == Column.OrderDirection.Ascendant ? query.OrderBy(x => x.CompanyTypeName) : query.OrderByDescending(x => x.CompanyTypeName);
                break;
        }
    }
    

    1. Then apply the paging using Skip and Take as before:

    e.g.

    var result = query.Skip(requestmodel.Start).Take(requestmodel.Length).Select(x => new { x.CompanyTypeName, x.CompanyTypeDescription });
    

    1. And finally return the JSON result using the DataTablesResponse object:

    e.g.

    return Json(new DataTablesResponse(requestmodel.Draw, result, query.Count(), base.RefSureContext.CompanyType.Count()), JsonRequestBehavior.AllowGet);
    

    This simplified all the searching, sorting & paging into a nice easy to repeat pattern.

    The documentation for the addin is here.

    这篇关于JQuery的数据表服务器端分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆