码迷,mamicode.com
首页 > Web开发 > 详细

【干货】Jquery.Datables与Bootstrap3的组合使用

时间:2017-12-04 00:51:23      阅读:300      评论:0      收藏:0      [点我收藏+]

标签:color   submit   array   java   ble   data   动作   init   new   

官方地址


datatables官方网址:www.datatables.net

下载bootstrap3与datables文件包

引用文件


  • css:bootstrap.css、dataTables.bootstrap.css
  • js:jquery.js、jquery.dataTables.js、dataTables.bootstrap.js

 

不说废话,上干货

demo的实现


 

1、新建MVC空项目

2、在Models文件夹下新建Person.cs模型类

  Person.cs代码:

技术分享图片
    public class Person
    {
        public int PersonID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime AddTime { get; set; }
    }
View Code

3、添加HomeController控制器,在Index动作方法中模拟添加200条数据用来展示。并返回Index.cshtml强类型视图

  HomeController代码:

技术分享图片
 public class HomeController : Controller
    {
        List<Person> personList;
        public ActionResult Index()
        {
            personList = new List<Person>();
            for (int i = 0; i < 200; i++)
            {
                personList.Add(new Person
                {
                    PersonID=i,
                     FirstName="辣条"+i,
                      LastName="小王子"+i,
                      AddTime=DateTime.Now.AddMinutes(i)
                });
            }

            return View(personList);
        }
    }
View Code

4、Index.cshtml强类型视图代码(未进行datables分页):

技术分享图片
@model IEnumerable<JqueryDataTablesBootstrapDemo.Models.Person>
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>jquery.datables.js与bootstrap3的组合使用</title>

</head>
<body>
    <div class="panel panel-default">
        <div class="panel-heading">
            <div class="panel-title">
                基本的datatables
            </div>
        </div>
        <div class="container">
            <table id="table_local" class="table table-bordered table-striped table-hover">
                <thead>
                    <tr>
                        <th>PersonID</th>
                        <th>FirstName</th>
                        <th>LastName</th>
                        <th>AddTime</th>
                    </tr>
                </thead>
                @if (Model.Count() > 0)
                {
                    <tbody>
                        @foreach (var p in Model)
                        {
                            <tr>
                                <td>@p.PersonID</td>
                                <td>@p.FirstName</td>
                                <td>@p.LastName</td>
                                <td>@p.AddTime.ToString("yyyy-MM-dd HH:mm:ss")</td>
                            </tr>
                        }
                    </tbody>
                }
            </table>
        </div>
    </div>
</body>
</html>
View Code

技术分享图片

5、添加引用文件,进行初始化分页展示:

技术分享图片
    <link href="~/Content/bootstrap-3.3.7/css/bootstrap.css" rel="stylesheet" />
    <link href="~/Content/DataTables-1.10.15/media/css/dataTables.bootstrap.css" rel="stylesheet" />

    <script src="~/Content/DataTables-1.10.15/media/js/jquery.js"></script>
    @*<script src="~/Content/bootstrap-3.3.7/js/bootstrap.js"></script>*@
    <script src="~/Content/DataTables-1.10.15/media/js/jquery.dataTables.js"></script>
    <script src="~/Content/DataTables-1.10.15/media/js/dataTables.bootstrap.js"></script>

    <script type="text/javascript">
        $(function () {
            $("#table_local").dataTable();
        });

    </script>
View Code

技术分享图片

6、修改分页配置,将分页显示成中文,并添加搜索框

技术分享图片
 $("#table_local").dataTable({
                //lengthMenu: [5, 10, 20, 30],//这里也可以设置分页,但是不能设置具体内容,只能是一维或二维数组的方式,所以推荐下面language里面的写法。
                paging: true,//分页
                ordering: true,//是否启用排序
                searching: true,//搜索
                language: {
                    lengthMenu: <select class="form-control input-xsmall"> + <option value="1">1</option> + <option value="10">10</option> + <option value="20">20</option> + <option value="30">30</option> + <option value="40">40</option> + <option value="50">50</option> + </select>条记录,//左上角的分页大小显示。
                    search: <span class="label label-success">搜索:</span>,//右上角的搜索文本,可以写html标签

                    paginate: {//分页的样式内容。
                        previous: "上一页",
                        next: "下一页",
                        first: "第一页",
                        last: "最后"
                    },

                    zeroRecords: "没有内容",//table tbody内容为空时,tbody的内容。
                    //下面三者构成了总体的左下角的内容。
                    info: "总共_PAGES_ 页,显示第_START_ 到第 _END_ ,筛选之后得到 _TOTAL_ 条,初始_MAX_ 条 ",//左下角的信息显示,大写的词为关键字。
                    infoEmpty: "0条记录",//筛选为空时左下角的显示。
                    infoFiltered: ""//筛选之后的左下角筛选提示,
                },
                paging: true,
                pagingType: "full_numbers",//分页样式的类型

            });
            $("#table_local_filter input[type=search]").css({ width: "auto" });//右上角的默认搜索文本框,不写这个就超出去了。
View Code

技术分享图片

7、此时展示的是200条数据的分页展示,并没有进行ajax请求进行分页,接下来介绍ajax请求分页

 

Ajax进行分页


1、添加HomeAjaxController控制器,并且添加Index动作与GetPeoples动作进行返回json数据。

名称类型描述
draw integerJS 请求次数计数器,每次发送给服务器后又原封返回.
recordsTotal integerJS 即没有过滤的记录数(数据库里总共记录数)
recordsFiltered integerJS 过滤后的记录数
data arrayJS 表中中需要显示的数据。
error stringJS 可选。你可以定义一个错误来描述服务器出了问题后的友好提示

 

 

 

 

 

  draw参数必须要从前台页面,不然会第一次调用可以使用,第二次+调用无法收到后台json数据.

  HomeAjaxController代码:

技术分享图片
using JqueryDataTablesBootstrapDemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace JqueryDataTablesBootstrapDemo.Controllers
{
    public class HomeAjaxController : Controller
    {
        List<Person> personList;

        public HomeAjaxController()
        {
            personList = new List<Person>();
            for (int i = 0; i < 200; i++)
            {
                personList.Add(new Person
                {
                    PersonID = i,
                    FirstName = "辣条" + i,
                    LastName = "小王子" + i,
                    AddTime = DateTime.Now.AddMinutes(i)
                });
            }
        }


        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult GetPeoples(int start = 0, int length = 10, string disType = "", string name = "", int draw=0)
        {
            var data = personList.Skip(start).Take(length).ToList();
            return Json(new {
                data = data,
                draw = draw,
                recordsTotal = data.Count,
                recordsFiltered = personList.Count
            });
        }
    }
}
View Code

 

2、编写Index.cshtml代码:

技术分享图片
@{
    Layout = null;
}

@{
    //两种身份
    List<SelectListItem> discriminatorTypes = new List<SelectListItem>()
    {
        new SelectListItem(){Text="身份类型",Value = ""},
        new SelectListItem(){Text = "学生",Value ="Student"},
        new SelectListItem(){Text="导师",Value="Instructor"}
    };
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

    <link href="~/Content/bootstrap-3.3.7/css/bootstrap.css" rel="stylesheet" />
    <link href="~/Content/DataTables-1.10.15/media/css/dataTables.bootstrap.css" rel="stylesheet" />

    <script src="~/Content/DataTables-1.10.15/media/js/jquery.js"></script>
    @*<script src="~/Content/bootstrap-3.3.7/js/bootstrap.js"></script>*@
    <script src="~/Content/DataTables-1.10.15/media/js/jquery.dataTables.js"></script>
    <script src="~/Content/DataTables-1.10.15/media/js/dataTables.bootstrap.js"></script>

    <script type="text/javascript">
        $(function () {
            var tablePrefix = "#table_server_";
            $("#table_server").dataTable({
                serverSide: true,//分页,取数据等等的都放到服务端去
                processing: true,//载入数据的时候是否显示“载入中”
                pageLength: 10,//首次加载的数据条数
                ordering: false,//排序操作在服务端进行,所以可以关了。
                ajax: {//类似jquery的ajax参数,基本都可以用。
                    type: "post",//后台指定了方式,默认get,外加datatable默认构造的参数很长,有可能超过get的最大长度。
                    url: "@Url.Action("GetPeoples")",
                    dataSrc: "data",//默认data,也可以写其他的,格式化table的时候取里面的数据
                    data: function (d) {//d 是原始的发送给服务器的数据,默认很长。
                        var param = {};//因为服务端排序,可以新建一个参数对象
                        param.start = d.start;//开始的序号
                        param.length = d.length;//要取的数据的
                        param.draw = d.draw;//判断第几次调用,用来跟后端数据对接
                        var formData = $("#filter_form").serializeArray();//把form里面的数据序列化成数组
                        formData.forEach(function (e) {
                            param[e.name] = e.value;
                        });
                        return param;//自定义需要传递的参数。
                    },
                },
                columns: [//对应上面thead里面的序列
                    { data: "PersonID" },//字段名字和返回的json序列的key对应
                    { data: "FirstName" },
                    { data: "LastName" },
                    {
                        //Student 没有hireDate
                        data: function (e) {
                            if (e.AddTime) {//默认是/Date(794851200000)/格式,需要显示成年月日方式
                                return new Date(Number(e.AddTime.replace(/\D/g, ‘‘))).toLocaleDateString();
                            }
                            return "";
                        }
                    },
                    {
                        data: function (e) {//这里给最后一列返回一个操作列表
                            //e是得到的json数组中的一个item ,可以用于控制标签的属性。
                            return <a class="btn btn-default btn-xs show-detail-json"><i class="icon-edit"></i>显示详细</a>;
                        }
                    }
                ],
                initComplete: function (setting, json) {
                    //初始化完成之后替换原先的搜索框。
                    //本来想把form标签放到hidden_filter 里面,因为事件绑定的缘故,还是拿出来。
                    $(tablePrefix + "filter").html("<form id=‘filter_form‘>" + $("#hidden_filter").html() + "</form>");
                },
                language: {
                    lengthMenu: <select class="form-control input-xsmall"> + <option value="5">5</option> + <option value="10">10</option> + <option value="20">20</option> + <option value="30">30</option> + <option value="40">40</option> + <option value="50">50</option> + </select>条记录,//左上角的分页大小显示。
                    processing: "载入中",//处理页面数据的时候的显示
                    paginate: {//分页的样式文本内容。
                        previous: "上一页",
                        next: "下一页",
                        first: "第一页",
                        last: "最后一页"
                    },

                    zeroRecords: "没有内容",//table tbody内容为空时,tbody的内容。
                    //下面三者构成了总体的左下角的内容。
                    info: "总共_PAGES_ 页,显示第_START_ 到第 _END_ ,筛选之后得到 _TOTAL_ 条,初始_MAX_ 条 ",//左下角的信息显示,大写的词为关键字。
                    infoEmpty: "0条记录",//筛选为空时左下角的显示。
                    infoFiltered: ""//筛选之后的左下角筛选提示(另一个是分页信息显示,在上面的info中已经设置,所以可以不显示),
                }
            });
            //$("#table_server_filter input[type=search]").css({ width: "auto" });//右上角的默认搜索文本框,不写这个就超出去了。
        });
        $(document).on("submit", "#filter_form", function () {
            return false;
        });
        $(document).on("click", "#go_search", function () {
            $("#table_server").DataTable().draw();//点搜索重新绘制table。
        });
        $(document).on("click", ".show-detail-json", function () {//取出当前行的数据
            alert(JSON.stringify($("#table_server").DataTable().row($(this).parents("tr")).data()));
        });
    </script>
</head>
<body>
    <div class="hidden" id="hidden_filter">
        @* 把需要搜索的条件放到hidden里面,在table格式化完成的时候直接调用$.html()赋值,免去了在js拼接标签的麻烦 *@
        <div class="row" style="margin-right:0;">
            @Html.DropDownList("disType", discriminatorTypes, new { @class = "form-control input-small", style = "width:120px" })
            @Html.TextBox("name", "", new { @class = "form-control input-small", style = "width:150px", placeholder = "请输入姓名" })
            <button id="go_search" class="btn btn-default">搜索</button>
        </div>

    </div>

    <div class="panel panel-default">
        <div class="panel-heading">
            <div class="panel-title">
                Ajax 异步获取数据
            </div>
        </div>
        <div class="panel-body">
            <table id="table_server" class="table table-bordered table-striped table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>姓名</th>
                        <th>名</th>
                        <th>入职时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
            </table>
        </div>
    </div>
</body>
</html>
View Code

 

源码下载地址:http://download.csdn.net/download/qq_25153485/10143548

【干货】Jquery.Datables与Bootstrap3的组合使用

标签:color   submit   array   java   ble   data   动作   init   new   

原文地址:http://www.cnblogs.com/wyt007/p/7967289.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!