Bootstrap table Server paging and online editing application summary _javascript tips

Source: Internet
Author: User
Tags chrome developer

First look at the Bootstrap table application effect:

The table is used to display the data in the database, the data is loaded from the server by Ajax, and the paging function has the server implementation, avoids the client paging, and the user experience is bad when loading a large amount of data. You can also set the starting and ending time of the query data, and query the data for a certain time range. The online editing function is implemented using x-editable by extending the bootstrap table implementation.

There are two ways to use Bootstrap table:

1. Set the Data property to the normal table;

2. Enable the Bootstrap Table plug-in via JavaScript.

The first way is very convenient, but I prefer the second method, you can do JS and HTML separation, and JS code can be reused.

The documentation for the Bootstrap table is more detailed, but there are some specific things to look at, such as sample code.

First post and backstage the implementation of the code, and then specific introduction.

The front desk needs the resources file, mainly has the BOOTSTRAP3 related style, the JS as well as bootstrap table related CSS, JS and x-editable based on the Bootstrap3 style, 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-editable.js "></script>
<script Src= "//rawgit.com/vitalets/x-editable/master/dist/bootstrap3-editable/js/bootstrap-editable.js" ></script >

HTML code only needs

 

JS code, time query related code, query time set correctly, through the bootstrap table method refresh reload Data:

$ (' #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 set error ';
  }
  if (err) {
    $ (' #msg '). HTML (err + '! ');
    $ (' #msg '). FadeIn (1000);
  else {
    $ (' #msg '). HTML ("Committed!");
    $ (' #querylist '). Bootstraptable (' refresh ');
    $ (' #msg '). fadeout (3000);
  }
);

Table Related js:

$ (' #querylist '). Bootstraptable ({columns: [{field: ' Metermeasurehistoryid ', title: ' ID ', sortable:true }, {field: ' Value ', title: ' Values ', editable: {type: ' Text ', validate:function (value) {if (
        $.trim (value) = = ') {return ' measured value cannot be null '; }}, {field: ' Timestamp ', title: ' Time ', editable: {type: ' text ', validate:functi
        On (value) {if ($.trim (value) = = ') {return ' time cannot be empty '; }else if (!
        Date.parse (value)) {return ' time set error '; }}},{field: ' Operation ', title: ' Operations ', 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, SIDEP Agination: ' SerVer ', pagenumber:1, Pagesize:5, pagelist: [5, M], queryparams:function (params) {return {meter ID: $ (' #meterid '). Val (), PageSize:params.limit, Offset:params.offset, SortOrder:params.order, b
Egintime: $ (' #begintime '). Val (), Endtime: $ (' #endtime '). Val ()}, url: '/analyze/getjsonhistorydatas '}; window.operateevents = {' Click. Save ': function (E, value, row, index) {$.ajax ({type: Post), data:r
      ow, url: '/analyze/editmetermeasurehistorydata ', success:function (data) {alert (' modified successfully ');
  }
    }); }, ' click. Remove ': function (E, value, row, index) {$.ajax ({type: "Post", Data:row, url: '/ana
        Lyze/deletemetermeasurehistorydata ', success:function (data) {alert (' delete succeeded '); $ (' #querylist '). Bootstraptable (' Remove ', {field: ' Metermeasurehistoryid ', values: [Row.
      Metermeasurehistoryid]});
  }
    });}
}; 

The columns parameter sets all the columns of the table and the parameters for each column, and the field corresponds to the key value of the JSON-returned data and the column parameters in the bootstrap table; title corresponds to the column name displayed; Sortable settings sorted by current column Formatter the format of each cell in the column, editable sets how the current column cells are edited, and you can set the Validate authentication method.

So the actual table is set to four columns, sorted by column 1th, 2, 3 columns are editable, type is set to text, you can use other type as needed, column 2nd verifies data cannot be empty, 3rd column verifies input value is time; 1, 2, 3 column contents from server-returned JSON data The 4th column is the data operation on the current row and joins the listener event operateevents, bound to the window.

Sortname is set to the 1th column field value;

SortOrder set to reverse;

Pagination is a true representation of paging;

Sidepagination for server to represent servers paging;

PageNumber represents the default start page;

PageSize represents the number of data displayed per page;

PageList indicates the number of data displayed on each page of an optional;

Queryparams represents the parameters to be sent to the server each time you want to add the parameters you need;

The URL is the requested address of the data.

Viewing bootstrap-table.js, 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:pa
      Rams.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 backend implements three functions, one based on data loading, and data modification and deletion.

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 ()//Displays the most recent displaylength bar data if ("ASC" = order) {Historydatas = db.
    Metermeasurehistories.
    Where (p => p.metermeasure.meterid = = Meterid).
    By (P => p.timestamp).
    Skip (Displaystart). Take (displaylength). ToList ()//Displays the oldest displaylength bar data} int historydatatotal = db.
    Metermeasurehistories. Where (p => p.metermeasure.meterid = = Meterid). COUNT ()//Data total bar//Time filter 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 ()//Displays the most recent displaylength bar data if ("ASC" = order) {Historydatas = db.
      Metermeasurehistories.
      Where (p => p.metermeasure.meterid = = Meterid).
      Where (P => p.timestamp > BeginTime && p.timestamp < Endtime).
      By (P => p.timestamp).
      Skip (Displaystart). Take (displaylength). ToList ()//Displays the oldest displaylength data} historydatatotal = db.
      Metermeasurehistories.
      Where (p => p.metermeasure.meterid = = Meterid). Where (P => p.timestamp > BeginTime && p.timestamp < Endtime). Count ();//Data Total bar} 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 = Listmet
  Ermeasurehistories});
Return Content (jsondatatable); }

It implements pagination and data queries, returns JSON data, returns JSON data that includes total, rows two objects, totals represents the sum of data, and rows represents the data that needs 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 metermeasurehistoryid = Int. Parse (request["Metermeasurehistoryid"]);
  var metermeasurehistoryvalue = Double. Parse (request["Value"]);
  var metermeasurehistorytime = DateTime.Parse (request["Timestamp"));
  var metermeasurehistoryindb = db. Metermeasurehistories.find (Metermeasurehistoryid);
  Metermeasurehistoryindb.value = Metermeasurehistoryvalue;
  Metermeasurehistoryindb.timestamp = Metermeasurehistorytime;
  Db. SaveChanges ();
  var changeddata = new Metermeasurehistorydataviewmodels
    {
      Metermeasurehistoryid = Metermeasurehistoryindb.metermeasurehistoryid,
      Value = metermeasurehistoryindb.value,
      Timestamp = MetermeasurehistoryInDb.Timestamp.ToString ()
    };
  Jsonresult js = new Jsonresult ();
  Js. Data = Json (changeddata);
  return JS;
}

Data deletion function:

[HttpPost]
Public Jsonresult Deletemetermeasurehistorydata ()
{
  var metermeasurehistoryid = Int. Parse (request["Metermeasurehistoryid"]);
  Db. Metermeasurehistories.remove (db. Metermeasurehistories.find (Metermeasurehistoryid));
  Db. SaveChanges ();
  var deleteddata = new Metermeasurehistorydataviewmodels
  {
    Metermeasurehistoryid = Metermeasurehistoryid,
    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 via the Bootstrap table method remove.

Now use these, summed up the learning process, is to check the official documents, examples, look at the source code, and learn to use the Chrome Developer tool to view sources and network.

The above is a small set to introduce Bootstrap table Server page and online editing application summary, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.