基于BootstrapTable的简单应用

来源:互联网 发布:unity游戏优化 编辑:程序博客网 时间:2024/06/07 18:45

Bootstrap Table基于Bootstrap的jQuery表格插件,通过简单的设置,就可以拥有强大的单选、多选、排序、分页,以及编辑、导出、过滤(扩展)等等的功能。

本文将以一个基于BootstrapTable控件的图书列表查询功能为实例(如图1)。注意本实例使用了ASP.NET MVC。


图1

页面代码:

@{    Layout = null;    ViewBag.Title = "基于BootstrapTable的简单应用";}<!--添加相关样式引用--><link href="~/Content/bootstrap.min.css" rel="stylesheet" /><link href="~/Content/bootstrap-table.min.css" rel="stylesheet" /><div class="container body-content" style="padding-top:20px;">    <div class="panel panel-default">        <div class="panel-heading">查询条件</div>        <div class="panel-body">            <form class="form-inline">                <div class="row">                    <div class="col-sm-4">                        <label class="control-label">图书名称:</label>                        <input id="txtTitle" type="text" class="form-control">                    </div>                    <div class="col-sm-4">                        <label class="control-label">图书作者:</label>                        <input id="txtAuthor" type="text" class="form-control">                    </div>                    <div class="col-sm-4">                        <label class="control-label">出版社:</label>                        <input id="txtPublish" type="text" class="form-control">                    </div>                </div>                <div class="row text-right" style="margin-top:20px;">                    <div class="col-sm-12">                        <input class="btn btn-primary" type="button" value="查询" onclick="SearchData()">                        <input class="btn btn-default" type="button" value="批量删除" onclick="BtchDeleteBook()">                    </div>                </div>            </form>        </div>    </div>        <table id="table"></table></div><!--添加相关脚本引用--><script src="~/Scripts/jquery-1.10.2.min.js"></script><script src="~/Scripts/bootstrap.min.js"></script><script src="~/Scripts/bootstrap-table.min.js"></script><script src="~/Scripts/bootstrap-table-zh-CN.min.js"></script><script type="text/javascript">    $(document).ready(function () {        $('#table').bootstrapTable({            url: '@Url.Action("SearchBookInfo", "Home")',            queryParamsType: '',              //默认值为 'limit' ,在默认情况下 传给服务端的参数为:offset,limit,sort            queryParams: queryParams,            method: "post",            pagination: true,            pageNumber: 1,            pageSize: 2,            pageList: [10, 20, 50, 100],            sidePagination: "server",         //分页方式:client客户端分页,server服务端分页(*)            striped: true,                    //是否显示行间隔色            cache: false,            uniqueId: "BookId",               //每一行的唯一标识,一般为主键列            height:300,            paginationPreText: "上一页",            paginationNextText: "下一页",            columns: [                { checkbox: true },                { title: '序号', width: 50, align: "center", formatter: function (value, row, index) { return index + 1; } },                { title: '图书名称', field: 'Title' },                { title: '图书作者', field: 'Author' },                { title: '销售价格', field: 'Price' },                { title: '出版社', field: 'Publish' },                {                    title: '出版时间', field: 'PublishDate', formatter: function (value, row, index) {                        if (value == null)                            return "";                        else {                            var pa = /.*\((.*)\)/;                            var unixtime = value.match(pa)[1].substring(0, 10);                            return getShortTime(unixtime);                        }                    }                },                {                    title: '操作', field: 'BookId', formatter: function (value, row, index) {                        var html = '<a href="javascript:EditBook('+ value + ')">编辑</a>';                        html += ' <a href="javascript:DeleteBook(' + value + ')">删除</a>';                        return html;                    }                }            ]        });    });    //查询条件    function queryParams(params) {        return {            pageSize: params.pageSize,            pageIndex: params.pageNumber,            Title: $.trim($("#txtTitle").val()),            Author: $.trim($("#txtAuthor").val()),            Publish: $.trim($("#txtPublish").val()),        };    }    //查询事件    function SearchData() {        $('#table').bootstrapTable('refresh', { pageNumber: 1 });    }    //编辑操作    function EditBook(bookId){        alert("编辑操作,图书ID:" + bookId);    }    //删除操作    function DeleteBook(bookId) {        if (confirm("确定删除图书ID:" + bookId + "吗?"))        {            alert("执行删除操作");        }    }    //批量删除    function BtchDeleteBook(){        var opts = $('#table').bootstrapTable('getSelections');        if (opts == "") {            alert("请选择要删除的数据");        }        else {            var idArray = [];            for (var i = 0; i < opts.length; i++) {                idArray.push(opts[i].BookId);            }            if (confirm("确定删除图书ID:" + idArray + "吗?")) {                alert("执行删除操作");            }        }    }    function getTime(/** timestamp=0 **/) {        var ts = arguments[0] || 0;        var t, y, m, d, h, i, s;        t = ts ? new Date(ts * 1000) : new Date();        y = t.getFullYear();        m = t.getMonth() + 1;        d = t.getDate();        h = t.getHours();        i = t.getMinutes();        s = t.getSeconds();        // 可根据需要在这里定义时间格式        return y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d) + ' ' + (h < 10 ? '0' + h : h) + ':' + (i < 10 ? '0' + i : i) + ':' + (s < 10 ? '0' + s : s);    }    function getShortTime(/** timestamp=0 **/) {        var ts = arguments[0] || 0;        var t, y, m, d, h, i, s;        t = ts ? new Date(ts * 1000) : new Date();        y = t.getFullYear();        m = t.getMonth() + 1;        d = t.getDate();        // 可根据需要在这里定义时间格式        return y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d);    }</script>

控制器代码:

/// <summary>/// 查询图书信息/// </summary>/// <param name="param"></param>/// <returns></returns>public JsonResult SearchBookInfo(BookInfo param, int pageSize, int pageIndex){    //获取图书列表    List<BookInfo> bookList = GetBookList();    //根据条件筛选数据    if (!String.IsNullOrEmpty(param.Title))    {        bookList = bookList.Where(a => a.Title.Contains(param.Title)).ToList();    }    if (!String.IsNullOrEmpty(param.Author))    {        bookList = bookList.Where(a => a.Author.Contains(param.Author)).ToList();    }    if (!String.IsNullOrEmpty(param.Publish))    {        bookList = bookList.Where(a => a.Publish.Contains(param.Publish)).ToList();    }    //BootstrapTable的返回结果    BootstrapTableResult<BookInfo> result = new BootstrapTableResult<BookInfo>();    result.total = bookList.Count;    result.rows = bookList;    return Json(result);}/// <summary>    /// 获取图书列表    /// </summary>    /// <returns></returns>    public List<BookInfo> GetBookList(){    List<BookInfo> bookList = new List<BookInfo>();    BookInfo book1 = new BookInfo()    {        BookId = 8,        Title = "ASP.NET MVC 5高级编程",        Author = "加洛韦",        Publish = "清华大学出版社",        PublishDate = new DateTime(2017, 08, 15),        Price = 29.99    };    bookList.Add(book1);    BookInfo book2 = new BookInfo()    {        BookId = 9,        Title = "Java从入门到精通",        Author = "明日科技",        Publish = "清华大学出版社",        PublishDate = new DateTime(2015, 09, 28),        Price = 38.55    };    bookList.Add(book2);    BookInfo book3 = new BookInfo()    {        BookId = 10,        Title = "Oracle从入门到精通",        Author = "秦靖",        Publish = "机械工业出版社",        PublishDate = new DateTime(2014, 10, 08),        Price = 38.55    };    bookList.Add(book3);    return bookList;}

其他代码:

/// <summary>    /// 图书信息实体类    /// </summary>    public class BookInfo{    public int BookId { set; get; }             //图书ID        public string Title { set; get; }           //图书名称        public string Author { set; get; }          //图书作者      public string Publish { set; get; }         //出版社    public DateTime PublishDate { set; get; }   //出版时间        public Double Price { set; get; }           //销售价格    }

/// <summary>/// BootstrapTable返回结果类/// </summary>public class BootstrapTableResult<T>{    public int total { get; set; }      //总记录数    public List<T> rows { get; set; }   //数据列表}

Bootstrap Table资料网站:http://bootstrap-table.wenzhixin.net.cn/zh-cn/