Out-of-the-box application BootstrapTable, abpbootstraptable

Source: Internet
Author: User
Tags cloudflare

Out-of-the-box application BootstrapTable, abpbootstraptable

ABP is short for "ASP. NET Boilerplate Project (ASP. NET sample Project.

ASP. NET Boilerplate is a new starting point for developing modern WEB applications with best practices and popular technologies. It aims to become a general WEB application framework and project template.

ABC Official Website: http://www.aspnetboilerplate.com

Open source projects on Github: https://github.com/aspnetboilerplate

1. Introduction

In the previous article, the implementation of the page function of the ABC getting started series explains how to display pages by page, but its page display is only applicable to front-end web pages, and is not applicable to the background management system. Data presentation in the background management system is generally completed using some table plug-ins. In this section, we use BootstrapTable as an example.

2. BootstrapTable

The jQuery table plug-in based on Bootstrap provides powerful single-choice, multi-choice, sorting, paging, editing, export, filtering (Extension) functions through simple settings.

Bootstrap table is an open-source, lightweight, and rich front-end table plug-in. From the perspective of naming, we know that the style of the table is taken over by Bootstrap, so we don't have to worry about style adjustment. For more information, see the official documentation.

Let's get started with drills.

3. Practical drills

Because BootstrapTable is used for paging, the main difficulty lies in the plug-in configuration. Therefore, we will explain the main code this time. Please go to Github to view the source code.

3.1. Add the BackendTasksController

The controller mainly defines the list, create, and edit related actions. The most important method is the data binding Aciton GetAllTasks. The Code is as follows:

[DontWrapResult] public JsonResult GetAllTasks(int limit, int offset, string sortfiled, string sortway, string search, string status) { var sort = !string.IsNullOrEmpty(sortfiled) ? string.Format("{0} {1}", sortfiled, sortway) : ""; TaskState currentState; if (!string.IsNullOrEmpty(status)) Enum.TryParse(status, true, out currentState); var filter = new GetTasksInput { SkipCount = offset, MaxResultCount = limit, Sorting = sort, Filter = search }; if (!string.IsNullOrEmpty(status)) if (Enum.TryParse(status, true, out currentState)) filter.State = currentState; var pagedTasks = _taskAppService.GetPagedTasks(filter); return Json(new { total = pagedTasks.TotalCount, rows = pagedTasks.Items }, JsonRequestBehavior.AllowGet);}

The following describes the parameters one by one:

Limit: The paging parameter that specifies the maximum number of lines per page;

Offset: Specifies the offset of the paging parameter;

SortField: sorting parameter, sorting field;

SortWay: sorting parameter, sorting method (ascending or descending );

Search: filter parameter, specifying the name of the filtered task;

Status: filter parameter, specifying the status of the filtered task

Note that the parameter name and order must be consistent with that of the frontend parameter.

You may find that Action uses the [DontWrapResult] feature for modification, so that the returned json result will not be wrapped in the AbpJsonResult provided by the Abp. For more information about AbpJsonResult, see the Json formatting in the ABC getting started series.

3.2. Add List. cshtml for List display

The main code in List. cshtml is:

@ Using Abp. web. mvc. extensions @ {ViewBag. title = L ("BackendTaskList"); ViewBag. activeMenu = "BackendTaskList"; // Matches with the menu name in SimpleTaskAppNavigationProvider to highlight the menu item} <! -- Load the bootstrap-tablel style --> <link rel = "stylesheet" href =" http://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.0/bootstrap-table.min.css "Rel =" external nofollow "> @ section scripts {@ Html. Includescript ("~ /Views/backendtasks/list. js "); <! -- Load the script of bootstrap-tablel --> <script src =" http://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.0/bootstrap-table.min.js "> </Script> <! -- Latest compiled and minified Locales --> <script src =" http://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.0/locale/bootstrap-table-zh-CN.min.js "> </Script >}< div class =" row "> <div class =" panel-body "> <! -- Filter box --> <div class = "panel-default"> <div class = "panel-heading"> query condition </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-filter "> Task Name </label> <div class =" col-sm-3 "> <input type =" text "class =" form-control "id =" txt-filter "> </div> <label class =" control-label col-sm-1" = "Txt-search-status"> status </label> <div class = "col-sm-3"> @ Html. dropDownList ("TaskStateDropdownList", null, new {id = "txt-search-status", @ class = "form-control "}) </div> <div class = "col-sm-4" style = "text-align: left;"> <button type = "button" style = "margin-left: 50px "id =" btn-query "class =" btn-primary "> query </button> </div> </form> </div> </div> <! -- Bootstrap-the toolbar specified by tablel --> <div id = "toolbar" class = "btn-group"> <button id = "btn-add" type = "button" class = "btn-primary"> <span class = "glyphicon-plus" aria-hidden = "true"> </span> added </button> <button id = "btn -edit "type =" button "class =" btn-success "> <span class =" glyphicon-pencel "aria-hidden =" true "> </span> modify </button> <button id = "btn-delete" type = "button" class = "btn-da Nger "> <span class =" glyphicon-remove "aria-hidden =" true "> </span> Delete </button> </div> <! -- Bootstrap-table body --> <table id = "tb-tasks"> </table> </div> <! -- Load the Create task modal box in advance through initial page loading --> @ Html. Partial ("_ CreateTask") <! -- The edit task modal box is dynamically filled into this div through ajax --> <div id = "edit"> </div>

Because it is a demo, I directly use CDN to load css and js related to bootstrap table.

The filter box is defined first, and then the toolbar dedicated to bootstrap table is defined, which will be specified during subsequent bootstrap table initialization.

Use<table id="tb-tasks"></table>To define the bootstrap-table body.

3.3. Add list. js to initialize bootstrap table

During initialization, data binding, column name definition, sorting fields, paging, and event binding are performed for the specified data source in the bootstrap table.

Create a list. js file for initialization:

$ (Function () {// 1. initialize Table var oTable = new TableInit (); oTable. init (); // 2. initialize the Button click event var oButtonInit = new ButtonInit (); oButtonInit. init () ;}); var taskService = abp. services. app. task; var $ table = $ ('# tb-tasks'); var TableInit = function () {var oTableInit = new Object (); // initialize Table oTableInit. init = function () {$ table. bootstrapTable ({url: '/BackendTasks/GetAllTasks', // request background URL (*) method: 'get', // Request method (*) toolbar: '# toolbar', // container used by the tool button striped: true, // whether to display the row interval color cache: false, // whether to use the cache. The default value is true, therefore, you need to set this attribute (*) pagination: true, // whether to display the page (*) sortable: true, // whether to enable sorting sortOrder: "asc ", // sorting method queryParams: oTableInit. queryParams, // pass the parameter (*) sidePagination: "server", // paging mode: client page, server Page (*) pageNumber: 1, // initialize and load the first page. The default page is pageSize: 5. // The number of record lines per page (*) pageList: [10, 25, 50,100]. // The number of lines per page (*) search: false, // whether to display table search. this search is a client search and will not be performed on the server. Therefore, personally, it is of little significance to strictSearch: true, showColumns: true, // whether to display all the columns showRefresh: true, // whether to display the refresh button minimumCountColumns: 2, // The minimum allowed number of columns clickToSelect: true, // whether to enable the height of the selected row: 500, // The Row height. If the height attribute is not set, the table automatically considers the table height uniqueId: "Id" based on the number of records, // the unique identifier of each row, generally showToggle: true, // whether to display the switch button of the detailed view and List View cardView: false, // whether to display the detailed view detailView: false, // whether to display the Parent and Child table columns: [{radio: true}, {field: 'title', Title: 'Task name', sortable: true}, {field: 'description', title: 'Task description'}, {field: 'assignedpersonname', title: 'Task allocation'}, {field: 'state', title: 'Task status', formatter: showState}, {field: 'creationtime', title: 'creation date', formatter: showDate}, {field: 'operate', title: 'operation', align: 'center', valign: 'middle', clickToSelect: false, formatter: operateFormatter, events: operateEvents}]}) ;};

The parameter descriptions of bootstrap table Initialization Configuration in this section of JS have been commented out in the Code.

The following describes several important parameters:

3.3.1. queryParams query parameters

During initialization, we specified the query parameter:

QueryParams: oTableInit. queryParams, // pass the parameter (*)

The queryParams function is defined as follows:

// Specify the bootstrap-table query parameter oTableInit. queryParams = function (params) {var temp = {// The Name Of The key here and the variable name of the controller must be the same. Here, the controller needs to be changed to the same limit: params. limit, // page size offset: params. offset, // page number sortfiled: params. sort, // sorting field sortway: params. order, // search in ascending order: $ ("# txt-filter "). val (), // custom parameter-Task Name status: $ ("# txt-search-status "). val () // custom parameter passing-task status}; return temp ;};

Compare with the function name of the Action in the controller.public JsonResult GetAllTasks(int limit, int offset, string sortfiled, string sortway, string search, string status)The case and order of parameter names must be consistent with the query parameters defined in js.

3.3.2. Data Binding

Data Binding includes the following three parts:

Url: Specifies the URL of the request background;

Uniqueid: used to bind a unique ID column for each row. It is generally a primary key column.

Columns: used to bind the data to be displayed in each column.

For columns parameters, the field must be in the same case as the key of the json data returned by your request;

Title is the column name displayed;

Align specifies the horizontal method of the column;

Valign specifies the vertical alignment of columns;

Formatter is used to specify how columns are formatted and output. For example, if formatter: operateFormatter is specified in the Operation column, it is used to display operation groups in the same format;

// Specify the operation group function operateFormatter (value, row, index) {return ['<a class = "like" href = "javascript: void (0) "rel =" external nofollow "title =" Like "> ', '<I class = "glyphicon-heart"> </I>', '</a>', '<a class = "edit" href = "javascript: void (0) "rel =" external nofollow "title =" Edit "> ', '<I class = "glyphicon-edit"> </I>', '</a>', '<a class = "remove" href = "javascript: void (0) "rel =" external nofollow "title =" Remove "> ', '<I class = "glyphicon-remove"> </I>', '</a>']. join ('');}

Events is used to specify the events in the column. For example, events: operateEvents is specified in the Operation column to specify the event processing corresponding to each operation:

// Specify window for the table body operation event. operateEvents = {'click. like ': function (e, value, row, index) {alert ('You click like icon, row:' + JSON. stringify (row); console. log (value, row, index) ;}, 'click. edit': function (e, value, row, index) {editTask (row. id) ;}, 'click. remove ': function (e, value, row, index) {deleteTask (row. id );}};

3.3.3. toolbar event binding

The toolbar is in List. the add, edit, and delete buttons defined by cshtml. When initializing a table, you can directly specify the toolbar id for the toolbar parameter. For example, toolba: '# toolbar '. Where can I bind the toolbar button events? Go directly to the Code:

// Bootstrap-table toolbar button event initialization var ButtonInit = function () {var oInit = new Object (); var postdata ={}; oInit. init = function () {// initialize the button event on the page $ ("# btn-add "). click (function () {$ ("# add "). modal ("show") ;}); $ ("# btn-edit "). click (function () {var selectedRaido = $ table. bootstrapTable ('getselecexception'); if (selectedRaido. length = 0) {abp. policy. warn ("select the row to edit first! ");} Else {editTask (selectedRaido [0]. id) ;}}); $ ("# btn-delete "). click (function () {var selectedRaido = $ table. bootstrapTable ('getselecexception'); if (selectedRaido. length = 0) {abp. policy. warn ("select the row to be deleted first! ");} Else {deleteTask (selectedRaido [0]. id) ;}}); $ ("# btn-query "). click (function () {$ table. bootstrapTable ('refresh') ;}; return oInit ;};

This method will be called at the beginning of page loading:

var oButtonInit = new ButtonInit(); oButtonInit.Init();

In addition, the bootstrap table preset two useful functions are used in the function:

$ Table. bootstrapTable ('getselection'): Get table selection item $ table. bootstrapTable ('refresh'): refresh the table

4. Summary

This article mainly explains how to use bootstrap table for general background paging usage, and explains how to configure bootstrap table parameters and several precautions. Many of these functions are not mentioned. Please query the documentation for details.

Related Article

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.