JS component series - table component artifact: bootstrap table

Foreword: I have been busy with various effects before, but I don't know that the most basic Bootstrap Table usage is not involved, sin, sin. Make it up today. In the morning, the blogger used the Bootstrap Table from scratch from beginning to end. He encountered many problems in use, and also made some notes, which are shared here for the reference of gardeners who need to use it. I still remember that two days ago, a group of gardeners asked me about the use of Bootstrap Table. Haha, coincidentally, the blogger also encountered the same problem today. I still want to express my apologies for not posting this in advance.

Bootstrap table series:

1. Summary of related documents and technical websites

 Regarding the bootstrap of the streaming layout, the blogger has only started to use it in the last six months. After using it, he realized that the open source things are actually quite good. I would like to give a big compliment to the bootstrap open source workers! Old rules, post relevant documents:

Bootstrap Chinese website: http://www.bootcss.com/       

Bootstrap Table Demo:http://issues.wenzhixin.net.cn/bootstrap-table/index.html

Bootstrap Table API:http://bootstrap-table.wenzhixin.net.cn/zh-cn/documentation/

Bootstrap Table source code: https://github.com/wenzhixin/bootstrap-table

Bootstrap DataPicker:http://www.bootcss.com/p/bootstrap-datetimepicker/

Boostrap Table 扩展API:http://bootstrap-table.wenzhixin.net.cn/extensions/

Bootstrap Offline API

 Bootstrap Table Offline API

Here is a point to explain: the offline API of Bootstrap Table is saved by the blogger himself on the official website, and there may be problems with the style. Bloggers don't want to use this kind of obedient offline documentation, but there is no way . possibility of a wall. Is the next step to FQ, O(∩_∩)O~.

Second, the 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. The Bootstrap package can be found directly in  http://v3.bootcss.com/  . The version 4 has been previewed, but it is still recommended to use the relatively stable Bootstrap3, the latest 3.3.5. Then there is the Bootstrap Table package. Since it is open source, we can go directly to its source code https://github.com/wenzhixin/bootstrap-table and git it down. Then add these two packages to the project separately.

2. Use our amazing Nuget

Open Nuget and search for these two packages

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

And the version of Bootstrap Table turned out to be 0.4, which is too pitiful. So the blogger suggested 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.

3. Code Detailed Explanation

 Of course, the components are referenced in, and the use is simple, but there are many details involved that we need to deal with. We will talk about the details later. Let's take a look at the usage method first.

1. Reference the relevant components on the cshtml page and define an empty table.

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

    @*2, bootstrap component reference*@
    <script src="~/Content/bootstrap/bootstrap.js"></script>
    <link href="~/Content/bootstrap/bootstrap.css" rel="stylesheet" />
    
    @*3, Bootstrap table components and references to Chinese packages*@
    <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, the reference of the page Js file *@
    <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>
copy code

After importing the required files, the most important thing for us is to define an empty table, as above <table id="tb_departments"></table> . 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 in js, but bloggers feel that this usage is simple, but it is not It is too flexible, and it is not easy to handle these advanced usages such as parent-child tables, so we still use the table component in a unified way of initialization in js.

2. Js initialization

copy code
$(function () {

    // 1. Initialize Table 
    var oTable = new TableInit();
    oTable.Init ();

    // 2. Initialize the click event of the Button 
    var oButtonInit = new ButtonInit();
    oButtonInit.Init();

});


var TableInit = function () {
     var oTableInit = new Object();
     // Initialize Table 
    oTableInit.Init = function () {
        $('#tb_departments').bootstrapTable({
            url: '/Home/GetDepartment',          // Request background URL (*) 
            method: 'get',                       // Request method (*) 
            toolbar: '#toolbar',                 // Which container is used for tool buttons 
            striped: true ,                       / / Whether to display the line interval color 
            cache: false ,                        // Whether to use the cache, the default is true, so in general, this property needs to be set (*) 
            pagination: true ,                    // whether to display paging (*) 
            sortable: false ,                      // whether to enable sorting
            sortOrder: "asc",                    // sort method 
            queryParams: oTableInit.queryParams, // pass parameters (*) 
            sidePagination: "server",            // pagination method: client paging, server server paging (*) 
            pageNumber:1,                        // Initialize loading the first page, default first page 
            pageSize: 10,                        // Number of record rows per page (*) 
            pageList: [10, 25, 50, 100],         // Number of rows per page that can be selected (*) 
            search: true ,                        // Whether to display the form search, this search is a client-side search and will not enter the server side, so personally, it does not make much sense. 
            strictSearch: true ,
            showColumns: true ,                   // whether to display all columns 
            showRefresh: true ,                   // whether to display the refresh button 
            minimumCountColumns: 2,              // minimum allowed number of columns 
            clickToSelect: true ,                 // whether to enable click to select rows 
            height: 500,                         // rows High, if the height attribute is not set, the table will automatically feel the height of the table according to the number of records 
            uniqueId: "ID",                      // The unique identifier of each row, generally the primary key column 
            showToggle: true ,                     // Whether to display the switch between the detailed view and the list view button
            cardView: false ,                     // whether to display the detail view 
            detailView: false ,                    // whether to display the parent and child table 
            columns: [{
                checkbox: true
            }, {
                field: 'Name',
                title: 'Department name'
            }, {
                field: 'ParentName',
                title: 'Superior Department'
            }, {
                field: 'Level',
                title: 'Department level'
            }, {
                field: 'Desc',
                title: 'description'
            }, ]
        });
    };

    // Get the parameters of the query 
    oTableInit.queryParams = function (params) {
         var temp = {    // The name of the key here and the variable name of the controller must be the same. If this is changed, the controller also needs to be changed to the same 
            limit: params .limit,    // page size 
            offset: params.offset,   // page number 
            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 () {
         // Initialize the button event on the page 
    };

    return oInit;
};
copy code

The initialization of the table is also very simple, just define the relevant parameters. Some bloggers above have commented the important parameters, and the bloggers also marked the parameters necessary to initialize the Table with (*). If your table also has too many page requirements, you can directly use the necessary parameters. solve. Similarly, there are actually many parameters that need to be set in the columns parameter, such as column sorting, alignment, width and so on. These bloggers feel that it is relatively simple and will not involve the function of the table. Just look at the API and you will be able to do it.

3. The corresponding method in the Controller

copy code
     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 = " Sales " + i ;
                oModel.Level = i.ToString();
                oModel.Desc = " No description information yet " ;
                lstRes.Add(oModel);
            }

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

One thing to note here: if it is server-side paging, the returned result must contain two parameters, total and rows. Missing or wrong writing will cause the table to fail to display data. On the contrary, if it is client-side paging, here a collection object is returned to the front end.

4. Effect and description

 

Or post a few renderings:

4. Summary of the problem

Since the above functions are developed from scratch, bloggers can share with gardeners if they encounter a problem, which should 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 side, 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 will know how to pagination. And most importantly, the names of these two parameters must be total and rows. At the beginning, the blogger did not know this, and wrote total and row. The result is that the request can enter the GetDepartment method in the background, and the return values ​​of total and row also have values, but the front-end is displayed as follows:

I've been looking for the reason for a long time. It turns out that row is wrong, it should be written as rows. Maybe this is also the reason for the problem encountered by the gardeners the day before yesterday.

2. The second question is about the style of the bootstrap page. Friends who have used bootstrap should know that all the icons in it are written in the way of class = "glyphicon glyphicon-plus". The blogger did this as required, but the icons in front of adding, modifying, and deleting can't come out. as follows:

What's going on? Then all kinds of Baidu, and finally found that it was the problem of the fonts folder. When we create a new MVC project, we will automatically create a fonts folder with the following contents:

And our bootstrap.css is placed in the Content folder, so these style files cannot be found. Finally view the console via google chrome

It turns out that it automatically goes to the Content to find the fonts folder. It's easy to do now, just copy our fonts folder to Content. Oh, it turns out that this is the case, the problem is successfully solved.

3. About Chinese. At the beginning, the blogger did not refer to the package <script src="~/Content/bootstrap-table/locale/bootstrap-table-zh-CN.js"></script>, so the interface could not find the record, and the display was English, as follows:

Later, I also checked the information and learned that there was a Chinese package in the bootstrap table, just add it.

4. The fourth point is to talk about the search function that comes with the form. As you can see from the above, when the form is initialized, by setting search: true, the search box of the form can be set to appear and a fuzzy search can be performed. Previously, bloggers always thought that only client-side paging can use this search function. Thank you for pointing out that this search function can also be used for server-side paging. Just need to add the search parameter to the corresponding method. for example

copy code
oTableInit.queryParams = function (params) {
         var temp = {    // The name of the key here and the variable name of the controller must be the same. If this is changed, the controller also needs to be changed to the same 
            limit: params.limit,    // page Size 
            offset: params.offset,   // page number 
            departmentname: $("#txt_search_departmentname" ).val(),
            statu: $("#txt_search_statu").val(),
            search:params.search
        };
        return temp;
    };
copy code

then backend

copy code
 public JsonResult GetDepartment(int limit, int offset, string departmentname, string statu, string search)
        {
            var lstRes = new List<Department>();
            for (var i = 0; i < 50; i++)
            {
                var oModel = new Department ();
                oModel.ID = Guid.NewGuid().ToString();
                oModel.Name = " Sales " + i ;
                oModel.Level = i.ToString();
                oModel.Desc = " No description information yet " ;
                lstRes.Add(oModel);
            }

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

In this way, every time the user enters the search box, it will enter the background method, and pass the value entered by the user to the search parameter. However, if you need to perform fuzzy matching on multiple fields, it means that your background needs to perform like operations on multiple data fields, so the query efficiency is definitely low. Therefore, if there are many fields that need fuzzy matching, this search is not useful in actual projects. To sum up, bloggers still feel that the effect of this search is more obvious only when the client is paging.

5. Regarding the sorting of Bootstrap Table, since this BS system will definitely use server-side paging, if we only set attribute information such as sortable and sortOrder in js, the table will not be sorted effectively. The reason is very simple, the way of paging on the server side, sorting the data on this page makes little sense. Therefore, the general sorting needs to send the sorting method and sorting field to the background, and it is more appropriate to sort in the background. For example, we can add two more parameters here:

copy code
oTableInit.queryParams = function (params) {
         var temp = {    // The name of the key here and the variable name of the controller must be the same. If this is changed, the controller also needs to be changed to the same 
            limit: params.limit,    // page Size 
            offset: params.offset,   // page 
            order: params.order,
            ordername: params.sort,
            departmentname: $("#txt_search_departmentname").val(),
            statu: $("#txt_search_statu").val()
        };
        return temp;
    };
copy code

V. Summary

In the previous years of development experience, bloggers also used form components such as Jqgrid and EasyUI. In contrast, bootstrap Table has its own advantages:

1. The interface adopts a flat style, the user experience is better, and it is more compatible with various clients. This is also the most important.

2. Open source and free. People love it for free. Ha ha.

3. Compared with Jqgrid and easyUI, it is more lightweight. The functions cannot be said to be the most comprehensive, but they are basically sufficient.

At this point, this article is over, welcome gardeners to make bricks. Download the source code .

Recently, I plan to do something of my own and integrate some good technologies in the blog. Small partners who have project cooperation contact the blogger as soon as possible!

The original source of this article: http://www.cnblogs.com/landeanfen/

You are welcome to reprint, but without the consent of the author himself, after reprinting the article, you must give the author and the original link in an obvious position on the article page , otherwise you reserve the right to pursue legal responsibility!

 



Related: JS component series - table component artifact: bootstrap table