一般在利用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;
            }
        }
    }
}

大功告成!

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐