1. Introduction of Bootstrap Table
Regarding the introduction of Bootstrap Table, there are generally two methods:
1. Directly download the source code 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 Just 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, the use is simple, but it involves a lot of details that we need to deal with. We will talk about the details later. Let’s take a look at how to use it first.
1. Reference the relevant components in the cshtml page and define an empty table.
@{ Layout = null; }BootStrap Table使用 @*1、Jquery组件引用*@ @*2、bootstrap组件引用*@ @*3、bootstrap table组件以及中文包的引用*@ @*4、页面Js文件的引用*@查询条件
After introducing the required files, the most important thing for us is to define an empty table, as above
$(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. The corresponding method in Controller
public JsonResult GetDepartment(int limit, int offset, string departmentname, string statu) { var lstRes = new List(); 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); }
One thing to note here: if it is server-side paging, the returned result must contain two parameters: total and rows. Missing or incorrect writing will cause the table to be unable to display data. On the contrary, if it is client-side paging, a collection object should be returned to the front end.
4. Effects and description
Let’s post a few renderings:
3. Problem Summary
Since the above functions are developed from scratch, the blogger encountered I would like to share a question with my garden friends. This should also be the focus of today’s article.
1. As mentioned above, if the parameter sidePagination: "server" initialized in js is set to paginate on the server, then our return value must tell the front-end the total number of records and the number of records on the current page. , and then the front end knows how to paginate. And the most important thing is that the names of these two parameters must be total and rows. I didn’t know this at first, so I wrote total and row. The result is that the request can go to the GetDepartment method in the background. The return values total and row also have values, but the front end displays as follows:
找了好半天原因。原来是row写错了,应该写成rows。可能这也是前天园友遇到的问题的原因。
2、第二个问题就是关于bootstrap页面样式的问题,我们使用过bootstrap的朋友应该知道,它里面所有的图标都是通过class = "glyphicon glyphicon-plus"这种方式去写的。按要求这样做了,可是新增、修改、删除前面的图标怎么都出不来。如下:
怎么回事呢?然后各种百度,最后发现原来是fonts文件夹的问题。我们在新建一个MVC项目的时候,会自动创建一个fonts文件夹
而我们的bootstrap.css是放在Content文件夹里面的,这样就导致找不到这些样式文件。最终通过谷歌浏览器查看控制台
原来它自动去Content里面找fonts文件夹了。这下就好办了,把我们的fonts文件夹拷贝到Content下不就行了吗。呵呵,原来真是这样,问题顺利解决。
3、关于中文。刚开始,没有引用这个包,所以界面找不到记录是显示的是英文,如下:
后来也是查资料了解到,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) ? null : this.filterColumns; // Check filter this.data = f ? $.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 ? $.grep(this.data, function (item, i) { for (var key in item) { key = $.isNumeric(key) ? 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详解(基础版)相关文章请关注PHP中文网!