Home  >  Article  >  Web Front-end  >  Detailed explanation of JS table component artifact bootstrap table (basic version)_javascript skills

Detailed explanation of JS table component artifact bootstrap table (basic version)_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:27:091649browse

1. Introduction of Bootstrap Table

Regarding the introduction of Bootstrap Table, there are generally two methods:

1. Download the source code directly and add it to the project.
Since Bootstrap Table is a component of Bootstrap, it depends on Bootstrap. We first need to add a reference to Bootstrap.

2. Use our magical Nuget
Open Nuget and search for these two packages

Bootstrap is already the latest 3.3.5, we can install it directly.

The version of Bootstrap Table is actually 0.4, which is too cheating. Therefore, the blogger suggests that the Bootstrap Table package should be downloaded directly from the source code. The latest version of Bootstrap Table seems to be 1.9.0.

2. Detailed code explanation
Of course, once the component is referenced, it is easy to use. However, there are many details involved that need to be dealt with. We will talk about the details later. Let’s take a look at how to use it first.
1. Reference relevant components on the cshtml page and define an empty table.

@{
 Layout = null;
}
<!DOCTYPE html>
<html>
<head>
 <meta name="viewport" content="width=device-width" />
 <title>BootStrap Table使用</title>
 @*1、Jquery组件引用*@
 <script src="~/Scripts/jquery-1.10.2.js"></script>

 @*2、bootstrap组件引用*@
 <script src="~/Content/bootstrap/bootstrap.js"></script>
 <link href="~/Content/bootstrap/bootstrap.css" rel="stylesheet" />
 
 @*3、bootstrap table组件以及中文包的引用*@
 <script src="~/Content/bootstrap-table/bootstrap-table.js"></script>
 <link href="~/Content/bootstrap-table/bootstrap-table.css" rel="stylesheet" />
 <script src="~/Content/bootstrap-table/locale/bootstrap-table-zh-CN.js"></script>
 
 @*4、页面Js文件的引用*@
 <script src="~/Scripts/Home/Index.js"></script>
</head>
<body>
 <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">部门名称</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">状态</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" 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>
</body>
</html>

After introducing the required files, the most important thing for us is to define an empty table, as above 5067343eea259e0fe039107d7d02a143f16b1740fad44fb09bfe928bcc527e08 . Of course, Bootstrap table also provides a brief usage. You can directly define related attributes such as "data-..." in the table tag, so you don't need to register it in js. However, the blogger feels that although this usage is simple, it is not easy to use. It is too flexible and difficult to handle when encountering advanced usage such as parent-child tables, so we still use the table component by initializing it in js.
2. Js initialization

$(function () {

 //1.初始化Table
 var oTable = new TableInit();
 oTable.Init();

 //2.初始化Button的点击事件
 var oButtonInit = new ButtonInit();
 oButtonInit.Init();

});


var TableInit = function () {
 var oTableInit = new Object();
 //初始化Table
 oTableInit.Init = function () {
  $('#tb_departments').bootstrapTable({
   url: '/Home/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: true,      //是否显示表格搜索,此搜索是客户端搜索,不会进服务端,所以,个人感觉意义不大
   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: 'Name',
    title: '部门名称'
   }, {
    field: 'ParentName',
    title: '上级部门'
   }, {
    field: 'Level',
    title: '部门级别'
   }, {
    field: 'Desc',
    title: '描述'
   }, ]
  });
 };

 //得到查询的参数
 oTableInit.queryParams = function (params) {
  var temp = { //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的
   limit: params.limit, //页面大小
   offset: params.offset, //页码
   departmentname: $("#txt_search_departmentname").val(),
   statu: $("#txt_search_statu").val()
  };
  return temp;
 };
 return oTableInit;
};


var ButtonInit = function () {
 var oInit = new Object();
 var postdata = {};

 oInit.Init = function () {
  //初始化页面上面的按钮事件
 };

 return oInit;
};

The initialization of the table is also very simple, just define the relevant parameters. Some of the parameters that bloggers think are important above are annotated, and several parameters necessary to initialize the Table are also marked by bloggers with (*). If your table also has too many page requirements, just use the necessary parameters directly. solve. Similarly, there are actually many parameters that need to be set in the columns parameter, such as column sorting, alignment, width, etc. These bloggers think it is relatively simple and does not involve the functions of tables. They can just look at the API and get it done.
3. Corresponding methods in Controller

 public JsonResult GetDepartment(int limit, int offset, string departmentname, string statu)
  {
   var lstRes = new List<Department>();
   for (var i = 0; i < 50; i++)
   {
    var oModel = new Department();
    oModel.ID = Guid.NewGuid().ToString();
    oModel.Name = "销售部" + i ;
    oModel.Level = i.ToString();
    oModel.Desc = "暂无描述信息";
    lstRes.Add(oModel);
   }

   var total = lstRes.Count;
   var rows = lstRes.Skip(offset).Take(limit).ToList();
   return Json(new { total = total, rows = rows }, JsonRequestBehavior.AllowGet);
  }

这里有一点需要注意:如果是服务端分页,返回的结果必须包含total、rows两个参数。漏写或错写都会导致表格无法显示数据。相反,如果是客户端分页,这里要返回一个集合对象到前端。

4、效果及说明

还是贴几张效果图出来:

三、问题小结

由于是从零开始开发的以上功能,博主遇到一个问题可以和园友们分享一下,这应该也是今天这篇想表达的重点。

1、上面说过,如果在js里面初始化的参数sidePagination: "server" 设置为在服务端分页,那么我们的返回值必须告诉前端总记录的条数和当前页的记录数,然后前端才知道如何分页。并且最重要的一点,这两个参数的名字必须为total和rows。最开始也不知道这个,写成了total和row,结果是请求可以进到后台的GetDepartment方法,返回值total和row也都有值,可是前端就是显示如下:

找了好半天原因。原来是row写错了,应该写成rows。可能这也是前天园友遇到的问题的原因。

2、第二个问题就是关于bootstrap页面样式的问题,我们使用过bootstrap的朋友应该知道,它里面所有的图标都是通过class = "glyphicon glyphicon-plus"这种方式去写的。按要求这样做了,可是新增、修改、删除前面的图标怎么都出不来。如下:

怎么回事呢?然后各种百度,最后发现原来是fonts文件夹的问题。我们在新建一个MVC项目的时候,会自动创建一个fonts文件夹,里面内容如下:

而我们的bootstrap.css是放在Content文件夹里面的,这样就导致找不到这些样式文件。最终通过谷歌浏览器查看控制台

原来它自动去Content里面找fonts文件夹了。这下就好办了,把我们的fonts文件夹拷贝到Content下不就行了吗。呵呵,原来真是这样,问题顺利解决。

3、关于中文。刚开始,没有引用 9ee116a1f7acc6af8d288db8e0967ab52cacc6d41bbb37262a98f745aa00fbf0 这个包,所以界面找不到记录是显示的是英文,如下:

后来也是查资料了解到,bootstrap table里面原来还有一个中文包,把它添加进来就好了。

4、第四点要说说表格自带的搜索功能,有上可知,在初始化表格的时候,通过设置search: true可以设置表格的搜索框出现并且可以进行模糊搜索。但是这个时候问题来了,我们采用的是服务端分页,每次返回到前台的只有本页的数据,这个时候我们再搜索的时候发现:搜索不了。这是什么原因呢?博主在谷歌里面调试bootstrap-table.js这个js发现里面有这样一段逻辑:

 BootstrapTable.prototype.onSearch = function (event) {
  var text = $.trim($(event.currentTarget).val());

  // trim search input
  if (this.options.trimOnSearch && $(event.currentTarget).val() !== text) {
   $(event.currentTarget).val(text);
  }

  if (text === this.searchText) {
   return;
  }
  this.searchText = text;

  this.options.pageNumber = 1;
  this.initSearch();
  this.updatePagination();
  this.trigger('search', text);
 };

 BootstrapTable.prototype.initSearch = function () {
  var that = this;

  if (this.options.sidePagination !== 'server') {
   var s = this.searchText && this.searchText.toLowerCase();
   var f = $.isEmptyObject(this.filterColumns) &#63; null : this.filterColumns;

   // Check filter
   this.data = f &#63; $.grep(this.options.data, function (item, i) {
    for (var key in f) {
     if (item[key] !== f[key]) {
      return false;
     }
    }
    return true;
   }) : this.options.data;

   this.data = s &#63; $.grep(this.data, function (item, i) {
    for (var key in item) {
     key = $.isNumeric(key) &#63; parseInt(key, 10) : key;
     var value = item[key],
      column = that.columns[getFieldIndex(that.columns, key)],
      j = $.inArray(key, that.header.fields);

     // Fix #142: search use formated data
     if (column && column.searchFormatter) {
      value = calculateObjectValue(column,
       that.header.formatters[j], [value, item, i], value);
     }

     var index = $.inArray(key, that.header.fields);
     if (index !== -1 && that.header.searchables[index] && (typeof value === 'string' || typeof value === 'number')) {
      if (that.options.strictSearch) {
       if ((value + '').toLowerCase() === s) {
        return true;
       }
      } else {
       if ((value + '').toLowerCase().indexOf(s) !== -1) {
        return true;
       }
      }
     }
    }
    return false;
   }) : this.data;
  }
 };

在initSearch方法里面,它有一个判断:if (this.options.sidePagination !== 'server') {......}也就是说,如果不是服务端分页,才进入检索,重写加载表格,否则压根就不会进入检索,这也就是为什么服务分页的时候,搜索会不起作用。博主试了下,换成客户端分页,确实可以搜索。呵呵,原来如此。其实这也很好里面,过滤本页的数据,意义不大。
5、关于Bootstrap Table的排序,由于一般这种BS系统肯定会采用服务端分页,我们如果仅仅在js里面设置sortable和sortOrder等属性信息,表格是不会有效排序的。原因很简单,服务端分页的方式,排序本页数据意义不大。所以,一般的排序需要将排序方式和排序字段发送到后台,在后台排序比较合适。比如我们这里可以再参数里面增加两个:

oTableInit.queryParams = function (params) {
  var temp = { //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的
   limit: params.limit, //页面大小
   offset: params.offset, //页码
   order: params.order,
   ordername: params.sort,
   departmentname: $("#txt_search_departmentname").val(),
   statu: $("#txt_search_statu").val()
  };
  return temp;
 };

五、总结
在开发经历中,也使用Jqgrid、EasyUI等表格组件。相比而言,bootstrap Table有自己的优势:

1、界面采用扁平化的风格,用户体验比较好,更好兼容各种客户端。这点也是最重要的。

2、开源、免费。国人最喜欢的就是免费了。呵呵。

3、相对Jqgrid、easyUI而言,比较轻量级。功能不能说最全面,但基本够用。

以上就是本文的全部内容,希望能够帮助大家更好的学习JS表格组件神器bootstrap table。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn