Let’s first look at the effects of the Bootstrap Table:
The table is used to display the data in the database. The data is loaded from the server through AJAX. At the same time, the paging function is implemented by a server to avoid client paging and the user experience caused by poor loading of large amounts of data. You can also set the start and end time of querying data to query data for a certain time range. The online editing function is implemented by extending the Bootstrap Table and using X-editable.
There are two ways to use Bootstrap Table:
1. Set data attributes for ordinary tables;
2. Enable the Bootstrap Table plug-in through JavaScript.
The first method is very convenient, but I prefer the second method, which can separate JS and HTML, and the JS code can be reused.
The documentation of Bootstrap Table is relatively detailed, but there are some specific contents that need to be found in the sample code, etc.
First post the implementation code for the front and backend, and then introduce it in detail.
The resource files required by the front desk mainly include Bootstrap3-related styles, js, bootstrap Table-related css, js, and X-editable-based Bootstrap3-based styles and js:
<link rel="stylesheet" href="../assets/bootstrap/css/bootstrap.min.css"><link rel="stylesheet" href="../assets/bootstrap-table/src/bootstrap-table.css"><link rel="stylesheet" href="//rawgit.com/vitalets/x-editable/master/dist/bootstrap3-editable/css/bootstrap-editable.css"><script src="../assets/jquery.min.js"></script><script src="../assets/bootstrap/js/bootstrap.min.js"></script><script src="../assets/bootstrap-table/src/bootstrap-table.js"></script><script src="../assets/bootstrap-table/src/extensions/editable/bootstrap-table.js"></script><script src="//rawgit.com/vitalets/x-editable/master/dist/bootstrap3-editable/js/bootstrap-editable.js"></script>
HTML code only needs
<table id="querylist"></table>
JS code, time query related code, after the query time is set correctly, the data is refresh through the bootstrap Table method:
$('#submitgetdata').click(function () { $('#msg').html(''); var begintime_ = $('#begintime').val(); var endtime_ = $('#endtime').val(); var err = ''; if (begintime_ == '' || endtime_ == ''){ err = 'Query time cannot be empty'; }else if(Date.parse(endtime_)-Date.parse(begintime_) < 0){ err = 'Query time setting error'; } if (err) { $('#msg').html(err + '!'); $('#msg').fadeIn(1000); } else { $('#msg').html("Commit!"); $('#querylist').bootstrapTable('refresh'); $('#msg').fadeOut(3000); }});Table related js:
$('#querylist').bootstrapTable({ columns: [{ field: 'MeterMeasureHistoryID', title: 'ID', sortable: true }, { field: 'Value', title: 'value', editable: { type: 'text', validate: function(value) { if($.trim(value) == '') { return 'Measured value cannot be empty'; } } } } }, { field: 'Timestamp', title: 'Time', editable: { type: 'text', validate: function(value) { if($.trim(value) == '') { return 'Time cannot be empty'; }else if(!Date.parse(value)){ return 'Time setting error'; } } } } },{ field: 'operation', title: 'operation', formatter:function(value,row,index){ var s = '<a class = "save" href="javascript:void(0)">Save</a>'; var d = '<a class = "remove" href="javascript:void(0)">Delete</a>'; return s+' '+d; }, events: 'operateEvents' }], sortName: 'MeterMeasureHistoryID', sortOrder: 'desc', pagination: true, sidePagination: 'server', pageNumber: 1, pageSize: 5, pageList: [5, 10, 20], queryParams: function (params) { return { meterID: $('#meterid').val(), pageSize: params.limit, offset: params.offset, sortOrder: params.order, begintime: $('#begintime').val(), endtime: $('#endtime').val() } }, url: '/Analyze/GetJsonHistoryDatas'});window.operateEvents = { 'click .save': function (e, value, row, index) { $.ajax({ type: "post", data: row, url: '/Analyze/EditMeterMeasureHistoryData', success: function (data) { alert('Modified successfully'); } }); }, 'click .remove': function (e, value, row, index) { $.ajax({ type: "post", data: row, url: '/Analyze/DeleteMeterMeasureHistoryData', success: function (data) { alert('Delete Successfully'); $('#querylist').bootstrapTable('remove', { field: 'MeterMeasureHistoryID', values: [row.MeterMeasureHistoryID] }); } }); }};The columns parameter sets all columns of the table and the parameters of each column. Field corresponds to the key value of the data returned by json and the column parameters in the Bootstrap Table; the column name displayed according to the title; the sortable setting is sorted according to the current column; the formatter sets the format of each cell in the column; the editable setting is the editing method of the current column cell, and the validate verification method can also be set.
Therefore, the actual table is set to four columns, sorted according to the first column, columns 2 and 3 can be edited, type is set to text, and other types can be used as needed. The second column verification data cannot be empty, and the third column verification input value is time; the contents of columns 1, 2, and 3 come from the json data returned by the server; the fourth column is the data operation on the current row, and the listening event operateEvents is added, and bound to the window.
sortName is set to the field value in column 1;
sortOrder is set to reverse order;
pagination is true for pagination;
sidePagination represents server pagination;
pageNumber indicates the default start page;
pageSize represents the number of data displayed per page;
pageList represents the optional number of data displayed per page;
queryParams means that each parameter sent to the server can be added to the parameters you need;
url is the request address of the data.
Check bootstrap-table.js and you can see the default params parameters:
BootstrapTable.prototype.initServer = function (silent, query) { var that = this, data = {}, params = { pageSize: this.options.pageSize === this.options.formatAllRows() ? this.options.totalRows : this.options.pageSize, pageNumber: this.options.pageNumber, searchText: this.searchText, sortName: this.options.sortName, sortOrder: this.options.sortOrder }; if (!this.options.url) { return; } if (this.options.queryParamsType === 'limit') { params = { search: params.searchText, sort: params.sortName, order: params.sortOrder }; if (this.options.pagination) { params.limit = this.options.pageSize === this.options.formatAllRows() ? this.options.totalRows : this.options.pageSize; params.offset = this.options.pageSize === this.options.formatAllRows() ?: this.options.pageSize * (this.options.pageNumber - 1); } }The server background implements three functions, one is to load based on data, as well as modify and delete data.
public ActionResult GetJsonHistoryDatas(){ var displayStart = int.Parse(Request["offset"]); var displayLength = int.Parse(Request["pageSize"]); var meterID = int.Parse(Request["MeterID"]); var order = Request["sortOrder"]; var historyDatas = db.MeterMeasureHistories. Where(p => p.MeterMeasure.MeterID == meterID). OrderByDescending(p => p.Timestamp). Skip(displayStart). Take(displayLength).ToList();//Show the most recent displayLength data if ("asc" == order) { historyDatas = db.MeterMeasureHistories. Where(p => p.MeterMeasure.MeterID == meterID). OrderBy(p => p.Timestamp). Skip(displayStart). Take(displayLength).ToList();//Show the earliest displayLength data} int historyDataTotal = db.MeterMeasureHistories. Where(p => p.MeterMeasure.MeterID == meterID).Count();//Total number of data//Time filtering if (!String.IsNullOrEmpty(Request["begintime"])) { DateTime begintime = DateTime.Parse(Request["begintime"]); DateTime endtime = DateTime.Parse(Request["endtime"]); historyDatas = db.MeterMeasureHistories. Where(p => p.MeterMeasure.MeterID == meterID). Where(p => p.Timestamp > begintime && p.Timestamp < endtime). OrderByDescending(p => p.Timestamp). Skip(displayStart). Take(displayLength).ToList();//Show the most recent displayLength strip data if ("asc" == order) { historyDatas = db.MeterMeasureHistories. Where(p => p.MeterMeasure.MeterID == meterID). Where(p => p.Timestamp > begintime && p.Timestamp < endtime). OrderBy(p => p.Timestamp). Skip(displayStart). Take(displayLength).ToList();//Show the earliest displayLength data} historyDataTotal = db.MeterMeasureHistories. Where(p => p.MeterMeasure.MeterID == meterID). Where(p => p.Timestamp > begintime && p.Timestamp < endtime).Count();//Total number of data} List<MeterMeasureHistoryDataViewModels> ListMeterMeasureHistories = new List<MeterMeasureHistoryDataViewModels>(); foreach (var item in historyDatas) { ListMeterMeasureHistories.Add(new MeterMeasureHistoryDataViewModels { MeterMeasureHistoryID = item.MeterMeasureHistoryID, Value = item.Value, Timestamp = item.Timestamp.ToString() }); } string jsonDataTable = JsonConvert.SerializeObject( new { total = historyDataTotal, rows = ListMeterMeasureHistories }); return Content(jsonDataTable);}It implements pagination and data query, and returns json data. The returned json data includes two objects: total and rows. Total represents the total number of data, and rows represents the data to be displayed. MeterMeasureHistoryDateView is as follows, corresponding to the field value in Table:
public class MeterMeasureHistoryDataViewModels{ public int MeterMeasureHistoryID { get; set; } public double Value { get; set; } public string Timestamp { get; set; }}Data modification function:
[HttpPost]public JsonResult EditMeterMeasureHistoryData(){ var meterestehistoryid = int.Parse(Request["MeterMeasureHistoryID"]); var meterestehistoryvalue = double.Parse(Request["Value"]); var meterestehistorytime = DateTime.Parse(Request["Timestamp"]); var meterestehistoryInDb = db.MeterMeasureHistory.Find(meterestehistoryid); meteresteasurehistoryInDb.Value = meteresteasurehistoryvalue; meteresteasurehistoryInDb.Timestamp = meteresteasurehistorytime; db.SaveChanges(); var changedData = new MeterMeasureHistoryDataViewModels { MeterMeasureHistoryID = meteresteasurehistoryInDb.MeterMeasureHistoryID, Value = meteresteasurehistoryInDb.Value, Timestamp = meteresteasurehistoryInDb.Timestamp.ToString() }; JsonResult js = new JsonResult(); js.Data = Json(changedData); return js;}Data deletion function:
[HttpPost]public JsonResult DeleteMeterMeasureHistoryData(){ var meterestehistoryid = int.Parse(Request["MeterMeasureHistoryID"]); db.MeterMeasureHistory.Remove(db.MeterMeasureHistory.Find(meterestehistoryid)); db.SaveChanges(); var deletedData = new MeterMeasureHistoryDataViewModels { MeterMeasureHistoryID = meteresteasurehistoryid, Value = 0, Timestamp = null }; JsonResult js = new JsonResult(); js.Data = deletedData; return js;}After the server is deleted, the foreground deletes the specified data row through the bootstrap Table method.
I have used these things at the moment. To summarize the learning process, I am looking up official documents, examples, see the source code, and learn to use Chrome developer tools to view Sources and Network.
The above is the summary of the Bootstrap Table server pagination and online editing application introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!