ASP.NET MVC+Bootstrap个人博客之后台dataTable…

2018-06-22 06:00:47来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

  jQuery  dataTables 插件是一个优秀的表格插件,是后台工程师的福音!它提供了针对数据表格的排序、浏览器分页、服务器分页、查询、格式化等功能。dataTables 官网也提供了大量的演示和详细的文档进行说明,为了方便使用,这里进行详细说明。

      去官网:https://www.datatables.net/ 下载最新版本是v1.10.12。

在页面引入:

    <link rel="stylesheet" href="~/Content_Admin/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/Content_Admin/css/bootstrap-responsive.min.css" />
    <script type="text/javascript" src="~/Content_Admin/js/jquery.min.js"></script>
    <script type="text/javascript" src="~/Content_Admin/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="~/Content_Admin/js/jquery.dataTables.min.js"></script>

HTML代码:  写上<thead></thead>标头即可

 <div class="widget-content nopadding">
                    <table id="archives-table" class="table table-bordered data-table mydatatable">
                        <thead>
                            <tr>
                                <th>编号</th>
                                <th>标题</th>
                                <th>所属类别</th>
                                <th>浏览量</th>
                                <th>评论量</th>
                                <th>点赞量</th>
                                <th>状态</th>
                                <th>操作</th>
                                <th>操作</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>

客户端jQuery:

 $('#archives-table').dataTable({
                "oLanguage": {
                    //国际化
                    "sProcessing": "<img src='/Content_Admin/img/spinner.gif'>  努力加载数据中...",
                    "sLengthMenu": "每页显示&nbsp;_MENU_ &nbsp;条结果",
                    "sZeroRecords": "没有匹配结果",
                    "sInfo": "总共_PAGES_ 页,显示第_START_ 到第 _END_ ,筛选之后得到 _TOTAL_ 条,初始_MAX_ 条 ",
                    "infoEmpty": "0条记录", //筛选为空时左下角的显示"
                    "sInfoEmpty": "没有数据",
                    "sInfoFiltered": "(从_MAX_条数据中检索)",//筛选之后的左下角筛选提示,
                    "sZeroRecords": "没有检索到数据",
                    //"sSearch": '<span class="label label-success">&nbsp;搜索&nbsp;</span>'
                },

                //"bServerSide": false,  //第一种场景:服务端一次性取出所有数据,完全由客户端来处理这些数据.此时为false
                "bServerSide": true,  //第二种场景:服务端处理分页后数据,客户端呈现,此时为true.但此时aoColumns要变,将'sName'换成mDataProp,同时自定义列也要有对应的数据
                "sServerMethod": "GET",
                "sAjaxSource": "/Admin/AdminArchives/GetArchivesJson", //ajax Url地址
                "bProcessing": true,

                "bPaginate": true,
                "sPaginationType": "full_numbers",
                "bJQueryUI": true,  //客户端传给服务器的参数为sSearch
                'bFilter': false,
                //'bsearch':true,
                'bLengthChange': true,
                'aLengthMenu': [
                     [5, 15, 20, -1],
                     [5, 15, 20, "全部"] // change per page values here
                ],

                'iDisplayLength': 7,  //每页显示10条记录
                'bAutoWidth': true,
                "scrollX": true,

                "aoColumns": [
                     { "sWidth": "5%", "mDataProp": "Id" },
                     {
                         "sWidth": "40%",
                         "mDataProp": "Title",
                         "mRender": function (data, type, row) {
                             return '<a href="/Archives/Index/' + row.Id + '\">' + data + '</a>';
                         }
                     },
                     { "sWidth": "10%", "mDataProp": "CategoryName" },
                     { "sWidth": "6%", "mDataProp": "ViewCount", "bStorable": true },
                     { "sWidth": "6%", "mDataProp": "CommentCount", "bStorable": true },
                     { "sWidth": "6%", "mDataProp": "Digg", "bStorable": true },
                     {
                         "sWidth": "6%",
                         "mDataProp": "Status",
                         "mRender": function (data, type, row) {
                             var value = "已发布";
                             if (data == "0")
                                 value = "禁用";
                             return value;
                         }
                     },
                     { //自定义列 : 启用/禁用
                         "mDataProp": "null",
                         "sWidth": "6%",
                         "bSearchable": false,
                         "bStorable": false,
                         "mRender": function (data, type, row) {
                             var actionstr = '<a id="publicarticle" class="publicaction"  target-id="' + row.Id + '" href="#">发 布</a>';
                             if (row.Status == "1")
                                 actionstr = '<a id="delarticle" class="delaction" target-id="' + row.Id + '" href="#">禁 用</a>';
                             return actionstr;
                         }
                     },
                    { //自定义列 : real删除
                        "mDataProp": "null",
                        "sWidth": "6%",
                        "bSearchable": false,
                        "bStorable": false,
                        "mRender": function (data, type, row) {
                            return '<a id="realdelarticle"  class="tip" target-id="' + row.Id + '" href="#"><i class="icon-remove"></i></a>';
                        }
                    },
                     { //自定义列:编辑
                         "mDataProp": "null",
                         "sWidth": "6%",
                         "bSearchable": false,
                         "bStorable": false,
                         "mRender": function (data, type, row) {
                             return '<a class="tip" href="/Admin/AdminArchives/EditArchive/' + row.Id + '"><i class="icon-pencil"></i></a>';
                         }
                     }
                ],
                "aoColumnDefs": [
                    {
                        //报错:DataTables warning : Requested unknown parameter '1' from the data source for row 0
                        //加上这段定义就不出错了。
                        sDefaultContent: '',
                        aTargets: ['_all']
                    }
                ]
            });
jQuery

Jquery.DataTables插件的两种应用场景

场景一:服务端一次性取出所有数据,完全由客户端来处理这些数据.此时"bServerSide": false,

服务端代码:

 1  public JsonResult GetArchivesJson(jqDataTableParameter tableParam)
 2         {
 3              #region 1.0 场景一
 4             ////1. 获取所有文章
 5             //List<Article> DataSource = articleService.GetDataListBy(a => true, a => a.Id);
 6             ////2. 构造aaData
 7             //var data = DataSource.Select(a => new object[]{
 8             //  a.Id,
 9             //  a.Title+ "  ("+a.SubTime.ToString()+")",
10             //  (categoryService.GetDataListBy(c=>c.Id==a.CategoryId)[0]).Name,
11             //  a.ViewCount,
12             //  commentService.GetDataListBy(c=>c.CmtArtId==a.Id).Count,
13             //  a.Digg,
14             //  a.Status==1?"正常":"删除"
15             //});
16             ////3. 返回json,aaData是一个数组,数组里面还是字符串数组
17             //return Json(new
18             //{
19             //    sEcho = 1,
20             //    iTotalRecords = DataSource.Count,
21             //    iTotalDisplayRecords = data.Count(),
22             //    aaData = data
23             //}, JsonRequestBehavior.AllowGet); 
24             #endregion
25        }
public JsonResult GetArchivesJson(jqDataTableParameter tableParam)

场景二:服务端处理分页后数据,客户端呈现,此时为true,

服务端代码:

 1  public JsonResult GetArchivesJson(jqDataTableParameter tableParam)
 2         {
 3             #region 2.0 场景二
 4             //客户端需要"bServerSide": true, 用mDataProp绑定字段,obj.aData.Id获取字段(.属性)
 5 
 6             //0.0 全部数据
 7             List<Article> DataSource = articleService.GetDataListBy(a => true);
 8             //DataSource = DataSource.OrderByDescending(a => a.SubTime).ToList();
 9 
10             //1.0 首先获取datatable提交过来的参数
11             string echo = tableParam.sEcho;  //用于客户端自己的校验
12             int dataStart = tableParam.iDisplayStart;//要请求的该页第一条数据的序号
13             int pageSize = tableParam.iDisplayLength == -1 ? DataSource.Count : tableParam.iDisplayLength;//每页容量(=-1表示取全部数据)
14             string search = tableParam.sSearch;
15 
16             //2.0 根据参数(起始序号、每页容量、参训参数)查询数据
17             if (!String.IsNullOrEmpty(search))
18             {
19                 var data = DataSource.Where(a => a.Title.Contains(search) ||
20                                  a.Keywords.Contains(search) ||
21                                  a.Contents.Contains(search))
22                      .Skip<Article>(dataStart)
23                      .Take(pageSize)
24                      .Select(a => new
25                      {
26                          Id = a.Id,
27                          Title = a.Title + "  (" + a.SubTime.ToString() + ")",
28                          CategoryName = a.Category.Name,
29                          ViewCount = a.ViewCount,
30                          CommentCount = commentService.GetDataListBy(c => c.CmtArtId == a.Id).Count,
31                          Digg = a.Digg,
32                          Status = a.Status
33                      }).ToList();
34 
35                 //3.0 构造datatable所需要的数据json对象...aaData里面应是一个二维数组:即里面是一个数组[["","",""],[],[],[]]
36                 return Json(new
37                 {
38                     sEcho = echo,
39                     iTotalRecords = DataSource.Count(),
40                     iTotalDisplayRecords = DataSource.Count(),
41                     aaData = data
42                 }, JsonRequestBehavior.AllowGet);
43             }
44             else
45             {
46                 var data = DataSource.Skip<Article>(dataStart)
47                                      .Take(pageSize)
48                                      .Select(a => new
49                                      {
50                                          Id = a.Id,
51                                          Title = a.Title + "  (" + a.SubTime.ToString() + ")",
52                                          CategoryName = a.Category.Name,
53                                          ViewCount = a.ViewCount,
54                                          CommentCount = commentService.GetDataListBy(c => c.CmtArtId == a.Id).Count,
55                                          Digg = a.Digg,
56                                          Status = a.Status
57                                      }).ToList();
58 
59                 //3.0 构造datatable所需要的数据json对象...aaData里面应是一个二维数组:即里面是一个数组[["","",""],[],[],[]]
60                 return Json(new
61                 {
62                     sEcho = echo,
63                     iTotalRecords = DataSource.Count(),
64                     iTotalDisplayRecords = DataSource.Count(),
65                     aaData = data
66                 }, JsonRequestBehavior.AllowGet);
67             }
68             #endregion
69         }
public JsonResult GetArchivesJson(jqDataTableParameter tableParam)

其中dataTables发送的参数被分装在jqDataTableParameter.cs中:

 1   /// <summary>
 2     /// 在服务器端,可以通过以下请求参数来获得当前客户端的操作信息
 3     /// jquery $('selector').datatable()插件 参数model
 4     /// </summary>
 5     public class jqDataTableParameter
 6     {
 7         /// <summary>
 8         /// 1.0 DataTable用来生成的信息
 9         /// </summary>       
10         public string sEcho { get; set; }
11 
12         /// <summary>
13         /// 2.0分页起始索引
14         /// </summary>
15         public int iDisplayStart { get; set; }
16 
17         /// <summary>
18         /// 3.0每页显示的数量
19         /// </summary>
20         public int iDisplayLength { get; set; }
21 
22         /// <summary>
23         /// 4.0搜索字段
24         /// </summary>
25         public string sSearch { get; set; }
26 
27         /// <summary>
28         /// 5.0列数
29         /// </summary>
30         public int iColumns { get; set; }
31 
32         /// <summary>
33         /// 6.0排序列的数量
34         /// </summary>
35         public int iSortingCols { get; set; }
36 
37         /// <summary>
38         /// 7.0逗号分割所有的列
39         /// </summary>
40         public string sColumns { get; set; }
41     }
public class jqDataTableParameter

后台效果展示:

 以上就是对datatable插件的使用说明。

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:When using SqlDependency without providing an options value,

下一篇:自学asp.net mvc(二)