search
HomeWeb Front-endJS TutorialDetailed explanation of JS table component artifact bootstrap table (basic version)_javascript skills

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

. 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、关于中文。刚开始,没有引用 这个包,所以界面找不到记录是显示的是英文,如下:

后来也是查资料了解到,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
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.