JS component series - table component artifact: bootstrap table (3: final chapter, final dry goods welfare)

Foreword: I have introduced two articles about the basic usage of bootstrap table. In this chapter, we will continue to look at some of its more commonly used functions. Let’s end the article. Grandpa Mao told us that we must have a beginning and an end in doing things~~bootstrap table is something to think about. The function coverage seems unrealistic. The blogger has selected some functions that he thinks are more commonly used and shared them with gardeners here. The source code is also given here . Well, without further ado, let's start our dry goods journey.

Bootstrap table series:

1. Effect display

1. Table row style

 For example, we have a requirement to display the order page, orders in different states display different colors, as shown in the figure:

2. Inline editing of the table

In the first article, a gardener asked the blogger if he could support the effect of inline editing, and the answer was yes. Let's take a look at the effect first:

before editing

Click on a cell data

After editing after finishing

3. Merge table rows and columns

Bloggers think that the need for merging ranks and columns is very common, especially when making page reports. Let's take a look at the effect first:

 

The current page is not fully displayed, click to enter. how about it? The effect is not bad.

4, table data export

 Regarding table data export, bootstrap table supports three modes of export: basic, all, and selected. That is, current page data export, all data export, and selected data export. And it supports exporting various types of files, such as common excel, xml, json and other formats.

Export current page to excel

Export all table data

Export selected row data

 As for the export of other types of files, it is basically the same as excel, and the effect is not displayed.

Second, the table row style code example

 Regarding the style setting of the table row, the other is one of its most basic functions. Why put it in the third article? It's because bloggers feel that this feature may be used everywhere. Of course, the effect is not difficult. You can also use jQuery to set the background color of tr yourself, but bloggers feel that since bootstrap table provides a mechanism to set the background color of rows, why don't we use its built-in api. Let's see how to do it.

When initializing the form

copy code
     // Initialize Table 
        $( '#tb_order' ).bootstrapTable({
            url: '/TableStyle/GetOrder',          // 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, you need to set this property (*) 
            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 doesn't 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 detailed view 
            detailView: false ,                    // Whether to display the parent-child table 
            rowStyle: function (row, index) {
                 // There are 5 values ​​here to represent 5 colors ['active', 'success', 'info', 'warning', 'danger']; 
                var strclass = "" ;
                 if (row.ORDER_STATUS == "to be scheduled" ) {
                    strclass = 'success'; // there is one more active 
                }
                 else  if (row.ORDER_STATUS == "removed" ) {
                    strclass = 'danger';
                }
                else {
                    return {};
                }
                return { classes: strclass }
            },
            columns: [{
                checkbox: true
            }, {
                field: 'ORDER_NO',
                title: 'Order ID'
            }, {
                field: 'ORDER_TYPE',
                title: 'Order Type'
            }, {
                field: 'ORDER_STATUS',
                title: 'Order Status'
            }, {
                field: 'REMARK',
                title: 'Notes'
            }, ]
        });
copy code

In fact, the focus is on this parameter:

copy code
       rowStyle: function (row, index) {
                 // There are 5 values ​​here to represent 5 colors ['active', 'success', 'info', 'warning', 'danger']; 
                var strclass = "" ;
                 if (row.ORDER_STATUS == "to be scheduled" ) {
                    strclass = 'success'; // there is one more active 
                }
                 else  if (row.ORDER_STATUS == "removed" ) {
                    strclass = 'danger';
                }
                else {
                    return {};
                }
                return { classes: strclass }
            },
copy code

Bootstrap table supports the row background colors of the 5 tables, which are 'active', 'success', 'info', 'warning', 'danger'. As for each corresponding background color, just run the code. See. Regarding the return value of this method, the blogger also studied it for a long time when it was used for the first time. According to the rules of the bootstrap table, an object type in json format must be returned, such as: { classes: strclass } .

Third, the table inline editing code example

 Regarding inline editing of tables, several js files extended with bootstrap table are required.

1. Introduce additional js files

<link rel="stylesheet" href="//rawgit.com/vitalets/x-editable/master/dist/bootstrap3-editable/css/bootstrap-editable.css">
<script src="//rawgit.com/vitalets/x-editable/master/dist/bootstrap3-editable/js/bootstrap-editable.js"></script>
<script src="~/Content/bootstrap-table/extensions/editable/bootstrap-table-editable.js"></script>

2. When defining a table on a cshtml page, add two attributes

copy code
<table id="tb_departments">
        <thead>
            <tr>
                <th data-field="Name" data-editable="true">部门名称</th>
                <th data-field="ParentName">上级部门</th>
                <th data-field="Level" data-editable="true">部门级别</th>
                <th data-field="Desc" data-editable="true">描述</th>
            </tr>
        </thead>
    </table>
copy code

If it is initialized in js, it is written as follows:

{
         field: "name",
         title: "name" ,
         editable:true
}

3. Register and edit the saved event when initializing the form in js

copy code
$('#tb_departments').bootstrapTable({
            url: '/Editable/GetDepartment',          // Request the URL of the background (*) 
            method: 'get',                       // Request method (*) 
            toolbar: '#toolbar',                 // Which container is used for the tool button 
            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 (*) 
            onEditableSave: function (field, row, oldValue, $el) {
                $.ajax({
                    type: "post",
                    url: "/Editable/Edit",
                    data: { strJson: JSON.stringify(row) },
                    success: function (data, status) {
                        if (status == "success") {
                            alert( "edited successfully" );
                        }
                    },
                    error: function () {
                        alert("Error");
                    },
                    complete: function () {

                    }

                });
            }
        });
copy code

The point is to look at how this event is handled

copy code
       onEditableSave: function (field, row, oldValue, $el) {
                $.ajax({
                    type: "post",
                    url: "/Editable/Edit",
                    data: { strJson: JSON.stringify(row) },
                    success: function (data, status) {
                        if (status == "success") {
                            alert( "edited successfully" );
                        }
                    },
                    error: function () {
                        alert("Error");
                    },
                    complete: function () {

                    }

                });
            }
copy code

The corresponding method needs to handle the logic of saving by itself. The four parameters field, row, oldValue, and $el correspond to the name of the current column, the data object of the current row, the value before the update, and the jQuery object of the edited current cell.

Four, table row and column merge code example

 The row and column merging function of the table does not need to refer to other js files, and only needs to use the colspan and rowspan of the table on the cshtml page to achieve.

1. cshtml page

copy code
<table id="tb_report">
        <thead>
            <tr>
                <th colspan="4" data-valign="middle" data-align="center">第一季度</th>
                <th colspan="4" data-valign="middle" data-align="center">第二季度</th>
                <th colspan="4" data-valign="middle"</Q3>="center"data-alignth>
                <th colspan="4" data-valign="middle" data-align="center">第四季度</th>
                <th data-field="TotalCount" rowspan="2" data-valign="middle" data-align="center">年度汇总</th>
            </tr>
            <tr>
                <th data-field="JanCount" data-align="center"><>th</January
                th data-field="FebCount" data-align="center">二月</th>
                <th data-field="MarCount" data-align="center">三月</th>
                <th data-field="FirstQuarter" data-align="center">第一季度</th>

                <th data-field="AprCount" data-align="center">四月</th>
                <th data-field="MayCount" data-align="center">五月</th>
                <th data-field="JunCount" data-align="center">六月</th>
                <th data-field="SecondQuarter" data-align="center">第二季度</th>

                <th data-field="JulCount" data-align="center">七月</th>
                <th data-field="AguCount" data-align="center">八月</th>
                <th data-field="SepCount" data-align="center">九月</th>
                <th data-field="ThirdQuarter" data-align="center">第三季度</th>

                <th data-field="OctCount" data-align="center">十月</th>
                <th data-field="NovCount" data-align="center">十一月</th>
                <th data-field="DecCount" data-align="center">十二月</th>
                <th data-field="ForthQuarter" data-align="center">第四季度</th>
                
            </tr>
        </thead>
    </table>
copy code

2, js initialization is not special

copy code
$('#tb_report').bootstrapTable({
            url: '/GroupColumns/GetReport',          // 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 (*) 
            sortOrder: "asc",                    // sort by
            queryParams: oTableInit.queryParams, // pass parameters (*) 
            sidePagination: "server",            // paging mode: client paging, server server paging (*) 
            pageNumber: 1,                        // initialize the first page to load, the default is the first page One page 
            pageSize: 10,                        // Number of record rows per page (*) 
            pageList: [10, 25, 50, 100],         // Number of rows per page that can be selected (*) 
        });
copy code

How, is it very simple. Of course, someone said that you can use table attributes to set url, paging and other information directly in cshtml without js initialization. Indeed, if we look at its api, we will find that each property it initializes corresponds to a table property. type as

If your form doesn't have some special events to handle, this is perfectly fine.

Five, table data export code example

 The export function of tabular data also requires some extended js support.

1. Introduce additional js files

<script src="~/Content/bootstrap-table/extensions/export/bootstrap-table-export.js"></script>
<script src="//rawgit.com/hhurz/tableExport.jquery.plugin/master/tableExport.js"></script>

2. When js is initialized

copy code
     $('#tb_departments').bootstrapTable({
            url: '/Export/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: "client",            // 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 (*) 
            clickToSelect: true ,
            showExport: true ,                      // whether to show export 
            exportDataType: "basic",               // basic', 'all', 'selected'.columns 
            : [{
                checkbox: true
            }, {
                field: 'Name',
                title: 'Department name'
            }, {
                field: 'ParentName',
                title: 'Superior Department'
            }, {
                field: 'Level',
                title: 'Department level'
            }, {
                field: 'Desc',
                title: 'description'
            }, ]
        });
copy code

Let's look at the main point: these two properties

showExport: true ,                      // whether to show export 
exportDataType: "basic",               // basic', 'all', 'selected'.

showExport indicates whether to display the export button, and exportDataType indicates whether the export mode is the current page, all data or selected data.

6. Summary

The above is the effect of the function and the simple code to achieve. The blogger found several issues to be addressed.

1. The function of inline editing is to submit each cell to the background, which will cause frequent database operations, which is not suitable. I don't know if there is a better way to submit each line to the background.

2. Although the export function is very useful, unfortunately it does not support IE browser. The blogger has tried the example on the official website, and it seems that IE cannot export it. Pending verification.

The source code is provided, and gardeners can take a look if they are interested. 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 (3: final chapter, final dry goods welfare)