1. 程式人生 > >【幹貨】Jquery.Datables與Bootstrap3的組合使用

【幹貨】Jquery.Datables與Bootstrap3的組合使用

rec btn over pac .cn 拼接 blank com lin

官方地址


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的組合使用