bootstrap-table的一些基本使用及表內編輯的實現

最近工做須要接觸了bootstrap-table 因此研究了一下,並作了筆記,紅色位置要特別注意 javascript

前端主要使用了 jquery bootstrap-table  bootstrap-edittable  bootstrap-table-edittable.js  css

1)首頁咱們須要先引用css及js文件前端

<!---bootstrap使用的是3-->
<link href="/Content/bootstrap.min.css" rel="stylesheet" />
<link href="/Content/bootstrap-editable.css" rel="stylesheet" />
<link href="/Content/bootstrap-table.min.css" rel="stylesheet" />
<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/bootstrap.min.js"></script>
<!---行內編輯使用的 1.1.5-->
<script src="/Scripts/bootstrap-editable.js"></script>
<!--bootstrap-table中文包及js-->
<script src="/Scripts/bootstrap-table/bootstrap-table.min.js"></script>
<script src="/Scripts/bootstrap-table/locale/bootstrap-table-zh-CN.min.js"></script>
<!--封裝了bootstrap-table對x-editable的使用-->
<script src="/Scripts/bootstrap-table-editable.js"></script>
<!---一些其餘方法見 http://vitalets.github.io/x-editable/ --->

2)DOM書寫,包括表格用到的divjava

<div class="row">
    <div class="panel-body" style="padding-bottom:0px;">
        <div class="panel panel-default">
            <div class="panel-heading">查詢條件</div>
            <div class="panel-body">
                <form id="formSearch" class="form-horizontal">
                    <div class="form-group" style="margin-top:15px">
                        <label class="control-label col-sm-1" for="txt_search_departmentname">條件1</label>
                        <div class="col-sm-3">
                            <input type="text" class="form-control" id="txt_search_departmentname">
                        </div>
                        <label class="control-label col-sm-1" for="txt_search_statu">條件2</label>
                        <div class="col-sm-3">
                            <input type="text" class="form-control" id="txt_search_statu">
                        </div>
                        <div class="col-sm-4" style="text-align:left;">
                            <button type="button" style="margin-left:50px" id="btn_query" name="refresh" class="btn btn-primary">查詢</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        <div id="toolbar" class="btn-group">
            <button id="btn_add" type="button" class="btn btn-default">
                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
            </button>
            <button id="btn_edit" type="button" class="btn btn-default">
                <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
            </button>
            <button id="btn_delete" type="button" class="btn btn-default">
                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>刪除
            </button>
        </div>
        <table id="tb_departments"></table>

    </div>
</div>

 3)腳本的書寫jquery

  //(1)初始化
    $(function () {
        var oTable = new TableInit();
        oTable.Init();
    });
    var TableInit = function () {
        var oTableInit = new Object();
        oTableInit.Init = function () {
            $('#tb_departments').bootstrapTable({
                url: '/index/GetDepartment', //請求後臺的URL(*)
                method: 'get', //請求方式(*)
                toolbar: '#toolbar', //工具按鈕用哪一個容器
                striped: true, //是否顯示行間隔色
                cache: false, //是否使用緩存,默認爲true,因此通常狀況下須要設置一下這個屬性(*)
                pagination: true, //是否顯示分頁(*)
                sortable: false, //是否啓用排序
                sortOrder: "asc", //排序方式
                queryParams: oTableInit.queryParams,//傳遞參數(*)
                sidePagination: "server", //分頁方式:client客戶端分頁,server服務端分頁(*)
                pageNumber: 1, //初始化加載第一頁,默認第一頁
                pageSize: 10, //每頁的記錄行數(*)
                pageList: [10, 25, 50, 100], //可供選擇的每頁的行數(*)
                search: false, //是否顯示錶格搜索,此搜索是客戶端搜索,也能夠是服務端檢索
                strictSearch: true,
                showColumns: true, //是否顯示全部的列
                showRefresh: true, //是否顯示刷新按鈕
                minimumCountColumns: 2, //最少容許的列數
                clickToSelect: true, //是否啓用點擊選中行
                height: 500, //行高,若是沒有設置height屬性,表格自動根據記錄條數以爲表格高度
                uniqueId: "id", //每一行的惟一標識,通常爲主鍵列
                showToggle: true, //是否顯示詳細視圖和列表視圖的切換按鈕
                cardView: false, //是否顯示詳細視圖
                detailView: false, //是否顯示父子表
                columns: [{
                    checkbox: true
                }, {
                    field: 'one',
                    title: '列1',
                    editable: { type: 'text',
                        title: '用戶名',
                        validate: function (v) {
                            if (!v) return '用戶名不能爲空';
                        }
                    }
                    //驗證數字
                    //editable: {
                    //    type: 'text',
                    //    title: '年齡',
                    //    validate: function (v) {
                    //        if (isNaN(v)) return '年齡必須是數字';
                    //        var age = parseInt(v);
                    //        if (age <= 0) return '年齡必須是正整數';
                    //    }
                    //}
                    //時間框
                    //editable: {
                    //    type: 'datetime',
                    //    title: '時間'
                    //}
                    //選擇框
                    //editable: {
                    //    type: 'select',
                    //    title: '部門',
                    //    source: [{ value: "1", text: "研發部" }, { value: "2", text: "銷售部" }, { value: "3", text: "行政部" }]
                    //}
                    //複選框
                    //editable: {
                    //type: "checklist",
                    //separator:",",
                    //source: [{ value: 'bsb', text: '籃球' },
                    //     { value: 'ftb', text: '足球' },
                    //     { value: 'wsm', text: '游泳' }],
                    //}
                    //select2
                    //暫未使用到

                    //取後臺數據
                    //editable: {
                    //    type: 'select',
                    //    title: '部門',
                    //    source: function () {
                    //        var result = [];
                    //        $.ajax({
                    //            url: '/Editable/GetDepartments',
                    //            async: false,
                    //            type: "get",
                    //            data: {},
                    //            success: function (data, status) {
                    //                $.each(data, function (key, value) {
                    //                    result.push({ value: value.ID, text: value.Name });
                    //                });
                    //            }
                    //        });
                    //        return result;
                    //    }
                    //}


                }, {
                    field: 'two',
                    title: '列2',
                }],
                //保存的使用
                onEditableSave: function (field, row, oldValue, $el) {
                    //可進行異步操做

                    $.ajax({
                        type: "post",
                        url: "/index/Edit",
                        data: row,
                        dataType: 'JSON',
                        success: function (data, status) {
                            if (status == "success") {
                                alert('提交數據成功');
                            }
                        },
                        error: function () {
                            alert('編輯失敗');
                        },
                        complete: function () {

                        }

                    });
                }

            });
        };

        //獲得查詢的參數
        oTableInit.queryParams = function (params) {
            var temp = { //這裏的鍵的名字和控制器的變量名必須一直,這邊改動,控制器也須要改爲同樣的
                limit: params.limit, //頁面大小
                offset: params.offset, //頁碼
            };
            return temp;
        };
        return oTableInit;
    };

    //(2)關鍵字檢索
    $("#btn_query").click(function () {
        //點擊查詢是 使用刷新 處理刷新參數
        var opt = {
            url: "/index/GetDepartment",
            silent: true,
            query: {
                text1: $("#txt_search_departmentname").val(), //條件1
                text2: $("#txt_search_statu").val()           //條件2 ....
            }
        };
        $('#tb_departments').bootstrapTable('refresh', opt);

    });

    //(3)修改1、獲取編號進入下一頁
    $("#btn_edit").click(function () {
        var i = 0;
        var id;
        $("input[name='btSelectItem']:checked").each(function () {
            i++;
            id = $(this).parents("tr").attr("data-uniqueid");
        })
        if (i > 1) {
            alert("編輯只支持單一操做")
        } else {
            if (i != 0) {
                alert("獲取選中的id爲" + id);
                window.location.href = "/index/index";
            } else {
                alert("請選中要編輯的數據");
            }

        }

    })


    //(4)刪除及批量刪除

    $("#btn_delete").click(function () {
        if (confirm("確認要刪除嗎?")) {
            var idlist = "";
            $("input[name='btSelectItem']:checked").each(function () {
                idlist += $(this).parents("tr").attr("data-uniqueid") + ",";
            })
            alert("刪除的列表爲" + idlist);

        }
    });

</script>

 

 4)後臺獲取數據接口 index/GetDepartmentgit

 public JsonResult GetDepartment(int limit, int offset,string text1 = "",string text2 = "")
        {
            List<demo> demolist = new List<demo>();
            for (var i = 0; i < 100; i++)
            {
                demo d = new demo();
                d.id = i;
                d.one = "one" + i;
                d.two = "two" + i;
                demolist.Add(d);
            }
      
            if (text1 != "") {
                demolist = demolist.Where(a => a.one.Contains(text1)).ToList();
            }
            if (text2 != "") {
                demolist = demolist.Where(a =>  a.two.Contains(text2)).ToList();
            } 
            return Json(new { total = 100, rows = demolist.Skip(offset).Take(limit).ToList()}, JsonRequestBehavior.AllowGet);
        }

      public class demo
        {
            public int id { get; set; }

            public string one { get; set; }
            public string two { get; set; }
        }

 

5)行內編輯後臺保存github

        [HttpPost]
        //行內編輯使用
        public JsonResult Edit(demo user)
        {
            //邏輯

            return Json(new { }, JsonRequestBehavior.AllowGet);
        }

 

6)結果圖展現ajax

 

 7)js文件及css可下載源碼,源碼地址 https://github.com/MrsongJl/TableDemo/tree/master/TableDemo bootstrap

 8)使用自帶檢索修改初始化參數   search: true緩存

後臺接收search參數

9)若是你遇到表頭與表不對齊的問題,請去掉

相關文章
相關標籤/搜索