JS Table component Artifact Bootstrap table detailed (basic version) _javascript tips

Source: Internet
Author: User
Tags button type locale jqgrid

Introduction of Bootstrap Table

As for the introduction of bootstrap table, there are generally two methods:

1, directly download the source code, add to the project.
Since bootstrap table is a component of bootstrap, so it is dependent on bootstrap, we first need to add bootstrap references.

2, the use of our magical NuGet
Open NuGet, search these two packages

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

and bootstrap table version unexpectedly is 0.4, this also too pit dad. So the blogger suggested bootstrap table package directly in the source code to download it. Bootstrap table The latest version seems to be 1.9.0.

Second, the code detailed
of course, the component reference came in, the use is simple, but it involves a lot of details we need to deal with, we will say later, first look at the use of methods.
1, in the cshtml page to refer to the relevant components, and define a blank table.

@{Layout = null;} <! DOCTYPE html>  

After you introduce the required files, the most important thing is to define an empty table, such as the   <table id= "Tb_departments" ></table> . Of course bootstrap table also provides a description of the use, directly in the table label, such as "Data-..." and other related properties, you do not have to register JS, but the blogger felt that this usage is simple, but not too flexible, It is not very good to deal with these advanced usages such as parent-child tables, so let's use the table component in the way we initialize it in JS.
2, JS initialization

$ (function () {//1. initialize table var otable = new Tableinit ();

 Otable.init ();
 2. Initialize button's Click event 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 Mode (*) toolbar: ' #toolbar ',//tool button with which container striped:true,//whether to display row interval color cache:false,//whether to use the cache, default to T Rue, so you usually need to set this property (*) Pagination:true,//whether to display the paging (*) Sortable:false, or whether to enable sorting SortOrder: "ASC",//Sorting mode Querypara ms:otableinit.queryparams,//Pass Parameters (*) sidepagination: "Server",//Paging: Client Client page paging, Server service end Paging (*) pagenumber:1,// Initialize load first page, default first page pagesize:10,//page number of rows (*) PageList: [10, 25, 50, 100],//Available rows per page (*) Search:true,//whether to display a form search, this search is a guest User-side search, will not enter the service side, so, personal sense is not very strictsearch:true, showcolumns:true,//whether to display all columns showrefresh:true,//whether to show the refresh button Minimumcount Columns:2,//minimum allowable number of columns clicktoselect:true,//Whether to enable the Click Select Row height:500,//row height, if not set the Height property, the table automatically according to the number of records to feel the table height uniqueId: "ID",//each row unique identification, general primary key column showtoggle:true,//Whether it is obvious Toggle button Cardview:false For detailed views and list views,//whether to display a detailed view detailview:false,//whether to display a parent-child table columns: [{checkbox:true}, {field: ' N Ame ', title: ' Department name '}, {field: ' ParentName ', title: ' Parent Department '}, {field: ' Level ', title: ' Departmental '}, {field: ' Desc '
 , title: ' Description '},]};

 }; Parameters otableinit.queryparams = function (params) {var temp = {//Here's the name of the key and the variable name of the controller must always, this side changes, the controller also needs to change to the same limit:param S.limit,//Page size Offset:params.offset,//page Departmentname: $ ("#txt_search_departmentname"). Val (), Statu: $ ("#txt_sear
 Ch_statu "). Val ()};
 return temp;
 };
return otableinit;


};
 var buttoninit = function () {var oinit = new Object ();

 var postdata = {};

 Oinit.init = function () {//Initialize button events above the page;
return oinit;

 };

The initialization of the table is also very simple, the relevant parameters can be defined. Some of the above bloggers feel that important parameters are annotated, and initialization table must be several parameters bloggers also used (*) to do the tag, if your table also has too many page requirements, directly with the necessary parameters can be resolved. Also, there are many parameters that need to be set in the columns parameter, such as column sorting, alignment, width, and so on. These bloggers think it's simpler, and they don't involve the function of the table, and look at the API to fix it.
3, in the controller the corresponding method

 Public jsonresult getdepartment (int limit, int offset, string departmentname, String statu)
 {
 var lstres = new Lis T<department> ();
 for (var i = 0; i < i++)
 {
 var omodel = new Department ();
 Omodel.id = Guid.NewGuid (). ToString ();
 Omodel.name = "Sales Department" + I;
 Omodel.level = i.ToString ();
 Omodel.desc = "No descriptive information";
 Lstres.add (Omodel);
 }

 var total = Lstres.count;
 var rows = Lstres.skip (offset). Take (limit). ToList ();
 Return Json (New {total = total, rows = rows}, Jsonrequestbehavior.allowget);
 }

Here's one thing to note: If it is a service-side paging, the returned result must contain total, rows two parameters. Omitting or writing incorrectly can cause the table to not display data. Conversely, if it is a client page, here you return a collection object to the front end.

4, Effect and description

Or put a few pictures of the effect of the picture out:

Iii. Summary of issues

Because it is from the beginning of the development of the above features, bloggers encounter a problem can be shared with the park friends, this should also be the focus of today's expression.

1, said above, if the initialization in the JS parameter sidepagination: "Server" set to the service end paging, then our return value must tell the front end of the total number of records and the number of records on the current page, and then the front-end to know how to page. And most importantly, the names of the two parameters must be total and rows. The beginning also did not know this, written in total and row, the result is the request can go into the background of the Getdepartment method, return value total and row also have values, but the front-end is displayed as follows:

Looking for a reason. The original row was wrong, should be written rows. Maybe this is the reason for the problems that the friends of the garden met the day before yesterday.

2, the second question is about the bootstrap page style problem, we have used bootstrap friends should know that all of its icons are through class = "Glyphicon Glyphicon-plus" this way to write. As required to do so, but add, modify, delete the front of the icon how can not come out. As follows:

What's going on? Then all kinds of Baidu, finally found that the original is Fonts folder problem. When we build a new MVC project, we automatically create a Fonts folder with the following contents:

And our bootstrap.css are in the content folder, which causes the style files to be not found. Finally through the Google browser to view the console

Originally it automatically to content inside Find Fonts folder. This is a good place to do, the copy of our Fonts folder to the content of the right. Oh, the original really so, the problem solved smoothly.

3, about Chinese. At first, there was no reference to <script src= "~/content/bootstrap-table/locale/bootstrap-table-zh-cn.js" ></script> This package, so the interface can not find the record is displayed in English, as follows:

Later is also to check the data learned that bootstrap table inside the original there is a Chinese bag, add it in just fine.

4, the 4th to say that the form of the search function, there is known, in the initialization table, by setting Search:true can be set up a table search box appears and can be fuzzy search. But this time the problem comes, we are using the service end pagination, each return to the foreground only the data on this page, this time we search again found: Search. What's the reason? The blogger in the Google debugging bootstrap-table.js this JS found inside there is such a logic:

 BootstrapTable.prototype.onSearch = function (event) {var text = $.trim ($ (event.currenttarget). Val ()); Trim Search Input if (this.options.trimOnSearch && $ (event.currenttarget). Val ()!== text) {$ event.currentta
 Rget). 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 = this;
 if (this.options.sidePagination!== ' server ') {var s = this.searchtext && this.searchText.toLowerCase (); var f = $.isemptyobject (This.filtercolumns)?

 Null:this.filterColumns; Check filter this.data = f?
  $.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? $.grep (This.data, function (item, i) {for (var key in item) {key = $.isnumeric (key)?
  parseint (Key, ten): 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 (col
  Umn, 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 = = ' Numb
  Er ') {if (That.options.strictSearch) {if (value + '). toLowerCase () = = s) {return true;
  } else {if ((value + '). toLowerCase (). IndexOf (s)!==-1) {return true;
 }}} return false;
 }): This.data;
 }
 };

In the Initsearch method, it has a judgment: if (this.options.sidePagination!== ' server ') {...} That is, if it is not a service-side paging, then enter the search, rewrite the loading table, otherwise it will not go to the search, which is why the service pagination, the search will not work. Bo Master tried, replaced by the client page, you can really search. Oh, that's it. In fact, this is also very good inside, filter the data on this page, not very meaningful.
5, about the ranking of bootstrap table, because the general this BS system will certainly use service end paging, if we only in JS set sortable and sortorder and other attribute information, the table will not be effectively sorted. The reason is very simple, service-side paging way, sorting this page data does not mean much. So, the general sort needs to send the sort and sort fields to the background, sorting in the background is more appropriate. For example, we can add two additional parameters here:

Otableinit.queryparams = function (params) {
 var temp = {//Here's the name of the key and the variable name of the controller must always be changed here, the controller also needs to be changed to the same
 limit: Params.limit,//page size
 offset:params.offset,//pager
 Order:params.order,
 ordername:params.sort,
 Departmentname: $ ("#txt_search_departmentname"). Val (),
 Statu: $ ("#txt_search_statu"). Val ()
 };
 return temp;
 

V. Summary
In the development experience, also uses the Jqgrid, Easyui and so on the table component. In contrast, bootstrap table has its own advantages:

1, the interface using flat style, user experience is better, more compatible with a variety of clients. This is also the most important.

2, open source, free. What people like most is free. Oh.

3, relative Jqgrid, Easyui, relatively lightweight. Function can not be said the most comprehensive, but basic enough.

If you want to further study, you can click here to learn, and then attach two wonderful topics: Bootstrap Learning Tutorials Bootstrap actual combat Tutorials Bootstrap Table Use tutorials

The above is the entire content of this article, I hope to help you better learn the JS Table component Artifact bootstrap table.

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.