Bootstrap-Table表格內添加操作按鈕的實現方法

一般在利用Bootstrap-Table顯示後臺數據時,我們往往會在表格的最後一列添加操作按鈕,以便對某條數據進行修改和刪除操作,如下圖所示:
在這裏插入圖片描述
當點擊編輯按鈕時,界面會彈出模態框供用戶操作,點擊修改後表格自動刷新,如下圖所示:
在這裏插入圖片描述

測試數據

在這裏插入圖片描述

前端代碼

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Bootstrap Table</title>
    <link href="lib/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
    <link href="lib/bootstrap-table/bootstrap-table.min.css" rel="stylesheet" />
    <script src="lib/bootstrap/js/jquery-1.9.1.min.js"></script>
    <script src="lib/bootstrap/js/bootstrap.min.js"></script>
    <script src="lib/bootstrap-table/bootstrap-table.min.js"></script>
    <script src="lib/bootstrap-table/locale/bootstrap-table-zh-CN.min.js"></script>
</head>
<body>
    <div style="margin:100px auto;width:1000px;">
        <table id="table"></table>
    </div>

    <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="myModalLabel">編輯</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="id">編號</label>
                        <input id="id" type="text" class="form-control" disabled />
                    </div>
                    <div class="form-group">
                        <label for="name">姓名</label>
                        <input id="name" type="text" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label for="gender">性別</label>
                        <select id="gender" class="form-control">
                            <option value=""></option>
                            <option value=""></option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="age">年齡</label>
                        <input id="age" type="text" class="form-control" />
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">關閉</button>
                    <button type="button" class="btn btn-primary" onclick="editInfo()">修改</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        $('#table').bootstrapTable({
            url: "ashx/QueryHandler.ashx",                         // URL
            method: "post",                                        // 請求類型
            contentType: "application/x-www-form-urlencoded",      // post請求必須要有,否則後臺接受不到參數
            sidePagination: "server",                              // 設置在服務端還是客戶端分頁
            showRefresh: false,                                    // 是否刷新按鈕
            sortStable: true,                                      // 是否支持排序
            cache: false,                                          // 是否使用緩存
            pagination: true,                                      // 是否顯示分頁
            search: false,                                         // 是否有搜索框
            clickToSelect: true,                                   // 是否點擊選中行
            pageNumber: 1,                                         // 首頁頁碼,默認爲1
            pageSize: 5,                                           // 頁面數據條數
            pageList: [5, 10, 20, 30],
            queryParamsType: "",
            queryParams: function (params) {
                return {
                    pageSize: params.pageSize,                     // 每頁記錄條數
                    pageNumber: params.pageNumber,                 // 當前頁索引
                };
            },
            columns: [{
                field: 'Id',
                title: '編號',
                align: "center",
                halign: "center",
                valign: 'middle',
                sortable: true
            },
            {
                field: 'Name',
                title: '姓名',
                align: "center",
                halign: "center",
                valign: 'middle'
            },
            {
                field: 'Gender',
                title: '性別',
                align: "center",
                halign: "center",
                valign: 'middle'
            },
            {
                field: 'Age',
                title: '年齡',
                align: "center",
                halign: "center",
                valign: 'middle'
            },
            {
                field: 'operate',
                title: '操作',
                align: 'center',
                valign: 'middle',
                width: 200,
                events: {
                    'click #edit': function (e, value, row, index) {
                        $('#id').val(row.Id);
                        $('#name').val(row.Name);
                        $('#gender').val(row.Gender);
                        $('#age').val(row.Age);
                    },
                    'click #delete': function (e, value, row, index) {
                        deleteInfo(row.Id);
                    }
                },
                formatter: function (value, row, index) {
                    var result = "";
                    result += '<button id="edit" class="btn btn-info" data-toggle="modal" data-target="#editModal">編輯</button>';
                    result += '<button id="delete" class="btn btn-danger" style="margin-left:10px;">刪除</button>';
                    return result;
                }
            }]
        })

        // 修改信息
        function editInfo() {
            $.ajax({
                type: 'post',
                url: 'ashx/EditHandler.ashx',
                dataType: 'json',
                data: {
                    id: $('#id').val(),
                    name: $('#name').val(),
                    gender: $('#gender').val(),
                    age: $('#age').val()
                },
                success: function (data) {
                    if (data == 'Yes') {
                        $('#table').bootstrapTable('refresh');
                        $('#editModal').modal('hide');
                    }
                    else {
                        alert('修改失敗');
                    }
                }
            })
        }

        // 刪除信息
        function deleteInfo(id) {
            $.ajax({
                type: 'post',
                url: 'ashx/DeleteHandler.ashx',
                dataType: 'json',
                data: {
                    id: id
                },
                success: function (data) {
                    if (data == 'Yes') {
                        $('#table').bootstrapTable('refresh');
                    }
                    else {
                        alert('刪除失敗');
                    }
                }
            })
        }
    </script>
</body>
</html>

後臺查詢代碼

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json;

namespace WebApplication2.ashx
{
    /// <summary>
    /// TestHandler 的摘要說明
    /// </summary>
    public class QueryHandler : IHttpHandler
    {
        private static string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            // 獲取分頁參數
            int pageSize = int.Parse(context.Request["pageSize"].ToString());
            int pageNumber = int.Parse(context.Request["pageNumber"].ToString());

            // 查詢數據
            int total = GetCount();
            DataTable dataTable = GetDataTable(pageSize, pageNumber);

            // 格式化數據
            var data = new { total = total, rows = dataTable };
            context.Response.Write(JsonConvert.SerializeObject(data));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        // 數獲取數量
        private int GetCount()
        {
            string sql = "select count(*) from [TPerson]";
            using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
                SqlCommand command = new SqlCommand(sql, connection);
                try
                {
                    connection.Open();
                    return Convert.ToInt32(command.ExecuteScalar());
                }
                catch
                {
                    return -1;
                }
            }
        }

        // 分頁查詢
        private DataTable GetDataTable(int pageSize, int pageNumber)
        {
            string sql = "select * from(select row_number() over(order by Id) as RowId, *from [TPerson]) as b where b.Id between (@pageNumber - 1) * @pageSize + 1 and @pageNumber * @pageSize order by Id";
            using (SqlDataAdapter adapter = new SqlDataAdapter(sql.ToString(), ConnectionString))
            {
                SqlParameter[] parameters =
                {
                    new SqlParameter("@pageSize", pageSize),
                    new SqlParameter("@pageNumber", pageNumber)
                };
                
                DataTable dataTable = new DataTable();
                adapter.SelectCommand.Parameters.AddRange(parameters.ToArray());
                adapter.Fill(dataTable);
                return dataTable;
            }
        }
    }
}

後臺編輯代碼

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json;

namespace WebApplication2.ashx
{
    /// <summary>
    /// QueryHandler 的摘要說明
    /// </summary>
    public class EditHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            // 獲取參數
            int id = int.Parse(context.Request["id"].ToString());
            string name = context.Request["name"].ToString();
            string gender = context.Request["gender"].ToString();
            int age = int.Parse(context.Request["age"].ToString());

            // 查詢參數
            SqlParameter[] parameters =
            {
                new SqlParameter("@Id", id),
                new SqlParameter("@Name", name),
                new SqlParameter("@Gender", gender),
                new SqlParameter("@Age", age)
            };

            // 修改信息
            using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
            {
                SqlCommand command = new SqlCommand();
                command.Connection = connection;
                command.CommandText = "update [TPerson] set Name=@Name,Gender=@Gender,Age=@Age where Id=@Id";
                command.Parameters.AddRange(parameters);
                try
                {
                    connection.Open();
                    command.ExecuteNonQuery();
                    context.Response.Write(JsonConvert.SerializeObject("Yes"));
                }
                catch
                {
                    context.Response.Write(JsonConvert.SerializeObject("No"));
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

後臺刪除代碼

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json;

namespace WebApplication2.ashx
{
    /// <summary>
    /// DeleteHandler 的摘要說明
    /// </summary>
    public class DeleteHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            // 獲取參數
            int id = int.Parse(context.Request["id"].ToString());

            // 刪除信息
            using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
            {
                SqlCommand command = new SqlCommand();
                command.Connection = connection;
                command.CommandText = "delete from [TPerson] where Id=@Id";
                command.Parameters.Add(new SqlParameter("@Id", id));
                try
                {
                    connection.Open();
                    command.ExecuteNonQuery();
                    context.Response.Write(JsonConvert.SerializeObject("Yes"));
                }
                catch
                {
                    context.Response.Write(JsonConvert.SerializeObject("No"));
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

大功告成!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章