本实例引用Datatable版本号: 1.10.16

一、传到aspx后台(webmethod)

 

  1、添加js、css引用:

    <link href="/Scripts/ThirdLibs/DataTables/jquery.dataTables.min.css" rel="stylesheet" />
    <script src="/Scripts/ThirdLibs/DataTables/jquery.dataTables.min.js"></script>

 2、前台代码:

  

<div style="padding: 10px;">
        <input type="text" id="nickname" class="form-control" />
        <input type="button" value="搜索" id="search" class="btn btn-primary" />
    </div>

    <table id="tbSubscirptionReport" class="table table-hover table-striped table-bordered table-choose single-check">
        <thead>
            <tr>
                <th style="width: 5%">序号</th>
                <th style="width: 15%">表单号</th>
                <th style="width: 20%">资源名称</th>
                <th style="width: 10%">资源类型</th>
                <th style="width: 10%">审批状态</th>
                <th style="width: 10%">申请人姓名</th>
                <th style="width: 15%">申请时间</th>
                <th style="width: 15%">操作</th>
            </tr>
        </thead>

    </table>


    <%--js脚本--%>
    <script>

        var myTable;
        $(function () {
            myTable = initializeTable();

            $("#search").click(function () {
                reloadTable();
            });
        });

        function initializeTable() {

            var dutyTable = $("#tbTestReport").dataTable({
                /****************************************表格数据加载****************************************************/
                "serverSide": true,
                "ajax": function (data, callback, settings) {
                    //封装请求参数
                    var param = {};
                    param.draw = data.draw;
                    param.length = data.length;//页面显示记录条数,在页面显示每页显示多少项的时候
                    param.start = data.start;//开始的记录序号
                    param.pageIndex = (data.start / data.length) + 1;//当前页码
                    param.search = $("#searchStr").val();
                    //ajax请求数据
                    $.ajax({
                        type: "post",
                        //url: "/ajaxpage/testdatatablehandler.ashx?cmd=getTestData",
                        url: "testdatatable.aspx/test",
                        contentType: "application/json;charset=utf-8",//设置内容类型,即在页面中传递的方式及编码方式
                        cache: false, //禁用缓存
                        data: JSON.stringify({ data: param }), //传入组装的参数
                        dataType: "json",
                        success: function (resultData) {
                            var result = JSON.parse(resultData.d);
                            //setTimeout仅为测试延迟效果
                            setTimeout(function () {
                                //封装返回数据
                                var returnData = {};
                                returnData.draw = result.draw;//这里直接自行返回了draw计数器,应该由后台返回
                                returnData.recordsTotal = result.recordsTotal;//返回数据全部记录
                                returnData.recordsFiltered = result.recordsFiltered;//后台不实现过滤功能,每次查询均视作全部结果
                                returnData.data = result.data;//返回的数据列表

                                //调用DataTables提供的callback方法,代表数据已封装完成并传回DataTables进行渲染
                                //此时的数据需确保正确无误,异常判断应在执行此回调前自行处理完毕
                                callback(returnData);
                            }, 200);
                        }
                    });
                },
                
                "columns": [//列绑定
                    { "序号": "" },
                    { "data": "ApplyNumber" },
                    { "data": "ResourceName" },
                    { "data": "ResourceType" },
                    { "data": "ApprovalStatus" },
                    { "data": "ApplicantName" },
                    { "data": "CreateTime" },
                    { "操作": "" }
                ],
                "columnDefs": [//列定义
                    {
                        "targets": [0],
                        "data": "ID",
                        "render": function (data, type, full) {//全部列值可以通过full.列名获取,一般单个列值用data PS:这里的render是有多少列就执行多少次方法。。。不知道为啥
                            //return "<input type='checkbox' value='" + data + "' name='DataID'>";
                            return "";
                        }
                    },
                    {
                        "targets": [6],
                        "data": "CreateTime",
                        "render": function (data, type, full) {//全部列值可以通过full.列名获取,一般单个列值用data PS:这里的render是有多少列就执行多少次方法。。。不知道为啥
                            if (data == null || data.trim() == "") { return ""; }
                            else { var date = new Date(parseInt(data.slice(6))); return date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate(); }
                        }
                    },
                    {
                        "targets": [7],
                        "data": "ID",
                        "render": function (data, type, full) {//全部列值可以通过full.列名获取,一般单个列值用data PS:这里的render是有多少列就执行多少次方法。。。不知道为啥
                            return "<a style='text-decoration:none' class='btn btn-info' onclick=article_edit('资讯编辑','article-add.html','" + data + "') href='javascript:;' title='编辑'><i class='Hui-iconfont'>编辑</i></a>" +
                                " <a style='text-decoration:none' class='btn btn-info' onclick=article_del(this,'" + data + "') href='javascript:;' title='删除'><i class='Hui-iconfont'>删除</i></a>";
                        }
                    },

                    { "orderable": false, "targets": [0, 7] },// 是否排序
                    //{ "visible": false, "targets": [3, 5] }//是否可见
                ],
                "rowCallback": function (row, data, displayIndex) {//行定义
                    $(row).attr("class", "text-c");

                },
                "drawCallback": function (settings, json) { //每次画完后调用

                    var startIndex = this.api().context[0]._iDisplayStart;//获取到本页开始的条数
                    this.api().column(0).nodes().each(function (cell, i) {
                        //翻页序号连续
                        cell.innerHTML = startIndex + i + 1;
                    });
                },
                /****************************************表格数据加载****************************************************/
                /****************************************表格样式控制****************************************************/
                "dom": "t<'dataTables_info'il>p",//表格布局
                "language": {//语言国际化
                    "lengthMenu": "每页 _MENU_ 条",
                    "zeroRecords": "没有找到记录",
                    "info": "当前显示 _START_ 到 _END_ 条,共 _TOTAL_条",
                    "infoEmpty": "无记录",
                    "paginate":
                    {
                        "first": "首页",
                        "previous": "前一页",
                        "next": "后一页",
                        "last": "末页"
                    }
                },
                "pagingType": "full_numbers",//分页格式
                "processing": true,//等待加载效果
                "ordering": false,//排序功能
                /****************************************表格样式控制****************************************************/
            });

            return dutyTable;
        }
        //当你需要多条件查询,你可以调用此方法,动态修改参数传给服务器
        function reloadTable() {
            var oSettings = myTable.fnSettings();
            myTable.fnClearTable(0);
            myTable.fnDraw();
        }
    </script>

 3、后台代码(aspx)

 [WebMethod]
        public static string Test(TestDataTable data) {

            #region ===代码===
            int totalCount = 0;//所有的
            //int selCount = 0;//根据条件搜索到的 

            System.Linq.Expressions.Expression<Func<ResourceApply, Boolean>> p = a => true;
            if (!string.IsNullOrEmpty(data.search))
            {
                p = a => a.ResourceName.ToUpper().Contains(data.search.ToUpper());
            }

            var list = new ResourceApplyService().GenericService.GetListByPage(data.length, data.pageIndex, out totalCount, p, a => a.CreateTime, true).ToList();
            data.recordsFiltered = totalCount;
            data.recordsTotal = totalCount;
            data.data = list;

            JavaScriptSerializer jss = new JavaScriptSerializer();
            return jss.Serialize(data);
            #endregion ===代码===

        }

 

 4、 Model TestDataTable

 1   /// <summary>
 2     /// JqueryDataTable插件交互的DT格式的数据(DT参数区分大小写)
 3     /// </summary>
 4     public class TestDataTable
 5     {
 6         /// <summary>
 7         /// 请求次数(前端==》后端)
 8         /// </summary>
 9         public int draw { get; set; }
10 
11         /// <summary>
12         /// 总记录数(前端《==后端)
13         /// </summary>
14         public int recordsTotal { get; set; }
15 
16         /// <summary>
17         /// 过滤后的总记录数(前端《==后端)
18         /// </summary>
19         public int recordsFiltered { get; set; }
20 
21         /// <summary>
22         /// 记录开始索引(前端==》后端)
23         /// </summary>
24         public int start { get; set; }
25 
26         /// <summary>
27         /// PageIndex(前端==》后端)
28         /// </summary>
29         public int pageIndex { get; set; }
30 
31         /// <summary>
32         /// PageSize(前端==》后端)
33         /// </summary>
34         public int length { get; set; }
35         public string search { get; set; }
36         /// <summary>
37         /// 集合分页数据(前端《==后端)
38         /// </summary>
39         public System.Collections.IList data { get; set; }
40     }

 

二、ashx 版

1、前端代码:

其他都一样,js略有不同

  1     <%--js脚本--%>
  2     <script>
  3 
  4         var myTable;
  5         $(function () {
  6             myTable = initializeTable();
  7 
  8             $("#search").click(function () {
  9                 reloadTable();
 10             });
 11         });
 12 
 13         function initializeTable() {
 14 
 15             var dutyTable = $("#tbTestReport").dataTable({
 16                 /****************************************表格数据加载****************************************************/
 17                 "serverSide": true,
 18                 "ajax": function (data, callback, settings) {
 19                     //封装请求参数
 20                     var param = {};
 21                     param.draw = data.draw;
 22                     param.length = data.length;//页面显示记录条数,在页面显示每页显示多少项的时候
 23                     param.start = data.start;//开始的记录序号
 24                     param.pageIndex = (data.start / data.length) + 1;//当前页码
 25                     param.search = $("#searchStr").val();
 26                     //ajax请求数据
 27                     $.ajax({
 28                         type: "post",
 29                         url: "/ajaxpage/testdatatablehandler.ashx?cmd=getTestData",
 30                         //url: "testdatatable.aspx/test",
 31                         //contentType: "application/json;charset=utf-8",//设置内容类型,即在页面中传递的方式及编码方式
 32                         cache: false, //禁用缓存
 33                         data: { "data": JSON.stringify( param)}, //传入组装的参数
 34                         dataType: "json",
 35                         success: function (result) {
 36                             //var result = JSON.parse(resultData.d);
 37                             //setTimeout仅为测试延迟效果
 38                             setTimeout(function () {
 39                                 //封装返回数据
 40                                 var returnData = {};
 41                                 returnData.draw = result.draw;//这里直接自行返回了draw计数器,应该由后台返回
 42                                 returnData.recordsTotal = result.recordsTotal;//返回数据全部记录
 43                                 returnData.recordsFiltered = result.recordsFiltered;//后台不实现过滤功能,每次查询均视作全部结果
 44                                 returnData.data = result.data;//返回的数据列表
 45 
 46                                 //调用DataTables提供的callback方法,代表数据已封装完成并传回DataTables进行渲染
 47                                 //此时的数据需确保正确无误,异常判断应在执行此回调前自行处理完毕
 48                                 callback(returnData);
 49                             }, 200);
 50                         }
 51                     });
 52                 },
 53                 
 54                 "columns": [//列绑定
 55                     { "序号": "" },
 56                     { "data": "ApplyNumber" },
 57                     { "data": "ResourceName" },
 58                     { "data": "ResourceType" },
 59                     { "data": "ApprovalStatus" },
 60                     { "data": "ApplicantName" },
 61                     { "data": "CreateTime" },
 62                     { "操作": "" }
 63                 ],
 64                 "columnDefs": [//列定义
 65                     {
 66                         "targets": [0],
 67                         "data": "ID",
 68                         "render": function (data, type, full) {//全部列值可以通过full.列名获取,一般单个列值用data PS:这里的render是有多少列就执行多少次方法。。。不知道为啥
 69                             //return "<input type='checkbox' value='" + data + "' name='DataID'>";
 70                             return "";
 71                         }
 72                     },
 73                     {
 74                         "targets": [6],
 75                         "data": "CreateTime",
 76                         "render": function (data, type, full) {//全部列值可以通过full.列名获取,一般单个列值用data PS:这里的render是有多少列就执行多少次方法。。。不知道为啥
 77                             if (data == null || data.trim() == "") { return ""; }
 78                             else { var date = new Date(parseInt(data.slice(6))); return date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate(); }
 79                         }
 80                     },
 81                     {
 82                         "targets": [7],
 83                         "data": "ID",
 84                         "render": function (data, type, full) {//全部列值可以通过full.列名获取,一般单个列值用data PS:这里的render是有多少列就执行多少次方法。。。不知道为啥
 85                             return "<a style='text-decoration:none' class='btn btn-info' onclick=article_edit('资讯编辑','article-add.html','" + data + "') href='javascript:;' title='编辑'><i class='Hui-iconfont'>编辑</i></a>" +
 86                                 "&nbsp;<a style='text-decoration:none' class='btn btn-info' onclick=article_del(this,'" + data + "') href='javascript:;' title='删除'><i class='Hui-iconfont'>删除</i></a>";
 87                         }
 88                     },
 89 
 90                     { "orderable": false, "targets": [0, 7] },// 是否排序
 91                     //{ "visible": false, "targets": [3, 5] }//是否可见
 92                 ],
 93                 "rowCallback": function (row, data, displayIndex) {//行定义
 94                     $(row).attr("class", "text-c");
 95 
 96                 },
 97                 "drawCallback": function (settings, json) { //每次画完后调用
 98 
 99                     var startIndex = this.api().context[0]._iDisplayStart;//获取到本页开始的条数
100                     this.api().column(0).nodes().each(function (cell, i) {
101                         //翻页序号连续
102                         cell.innerHTML = startIndex + i + 1;
103                     });
104                 },
105                 /****************************************表格数据加载****************************************************/
106                 /****************************************表格样式控制****************************************************/
107                 "dom": "t<'dataTables_info'il>p",//表格布局
108                 "language": {//语言国际化
109                     "lengthMenu": "每页 _MENU_ 条",
110                     "zeroRecords": "没有找到记录",
111                     "info": "当前显示 _START_ 到 _END_ 条,共 _TOTAL_条",
112                     "infoEmpty": "无记录",
113                     "paginate":
114                     {
115                         "first": "首页",
116                         "previous": "前一页",
117                         "next": "后一页",
118                         "last": "末页"
119                     }
120                 },
121                 "pagingType": "full_numbers",//分页格式
122                 "processing": true,//等待加载效果
123                 "ordering": false,//排序功能
124                 /****************************************表格样式控制****************************************************/
125             });
126 
127             return dutyTable;
128         }
129         //当你需要多条件查询,你可以调用此方法,动态修改参数传给服务器
130         function reloadTable() {
131             var oSettings = myTable.fnSettings();
132             myTable.fnClearTable(0);
133             myTable.fnDraw();
134         }
135     </script>

 

 

2、后台代码:

 1 string json = "";
 2         HttpContext context;
 3         JavaScriptSerializer jss = new JavaScriptSerializer();
 4         Dictionary<string, object> dic = new Dictionary<string, object>();
 5         public void ProcessRequest(HttpContext context)
 6         {
 7             this.context = context;
 8             context.Response.ContentEncoding = Encoding.GetEncoding("utf-8");//避免出现乱码
 9             //接收浏览器 get/post 过来的参数cmd
10             string cmd = context.Request["cmd"].ToString();
11             switch (cmd)
12             {
13                 case "getTestData":
14                     json = GetUserList();
15                     break;
16             }
17             context.Response.Write(json);
18         }
19         /// <summary>
20         /// 获得用户列表
21         /// </summary>
22         /// <param name="index"></param>
23         /// <returns></returns>
24         public string GetUserList()
25         {
26             #region ===代码===
27 
28             var dataStr = context.Request["Data"];
29             if(string.IsNullOrEmpty(dataStr))
30             {
31                 return "";
32             }
33             TestDataTable myData = Newtonsoft.Json.JsonConvert.DeserializeObject<TestDataTable>(dataStr);
34 
35             int totalCount = 0;//所有的
36             //int selCount = 0;//根据条件搜索到的 
37 
38             System.Linq.Expressions.Expression<Func<ResourceApply, Boolean>> p = a => true;
39             if (!string.IsNullOrEmpty(myData.search))
40             {
41                 p = a => a.ResourceName.ToUpper().Contains(myData.search.ToUpper());
42             }
43 
44             var list = new ResourceApplyService().GenericService.GetListByPage(myData.length, myData.pageIndex, out totalCount, p, a => a.CreateTime, true).ToList();
45             myData.recordsFiltered = totalCount;
46             myData.recordsTotal = totalCount;
47             myData.data = list;
48 
49             JavaScriptSerializer jss = new JavaScriptSerializer();
50             return jss.Serialize(myData);
51             #endregion ===代码===
52 
53         }

 

PS:这句是取当前页,指定length条数的数据,这个取数据自己实现

1 new ResourceApplyService().GenericService.GetListByPage(myData.length, myData.pageIndex, out totalCount, p, a => a.CreateTime, true).ToList();

 

posted on 2018-12-26 16:22  慕凡尘  阅读(1620)  评论(0编辑  收藏  举报