bootstrap table 服务器端分页--ashx+ajax

1.准备静态页面

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5     <title></title>
 6     <meta charset="utf-8" />
 7     <link rel="stylesheet" href="../Content/bootstrap.min.css">
 8     <link rel="stylesheet" href="../Content/bootstrap-table.css">
 9     <script src="../Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
10     <script src="../Scripts/bootstrap.min.js"></script>
11     <script src="../Scripts/bootstrap-table.js"></script>
12     <script src="../Scripts/bootstrap-table-zh-CN.min.js" type="text/javascript"></script>
13     <script src="js/list2.js" type="text/javascript"></script>
14 </head>
15 <body>
16     <iframe src="nav.html" height="50" width="100%" frameborder="0" scrolling="no"></iframe>
17     <p>用bootstrap table显示数据列表</p>
18     <table id="table">
19         <thead>
20             <tr>
21                 <th data-field="state" data-checkbox="true"></th>
22                 <th data-field="adminID" data-sortable="true" data-align="center">编号</th>
23                 <th data-field="LoginID" data-align="center">登录名</th>
24                 <th data-field="AdminName" data-align="center">真实姓名</th>
25                 <th data-field="sex" data-align="center" data-formatter="SEXFormatter">性别</th>
26                 <th data-field="adminID" data-align="center" data-formatter="editFormatter">操作</th>
27             </tr>
28 
29         </thead>
30     </table>
31     <input id="BtnDel" type="button" value="删除" />
32 </body>
33 </html>
list2.html

2.写js代码

$(document).ready(function () {

    
                   $('#table').bootstrapTable({
                    url:"ashx/list2.ashx",//数据源
                    sidePagination: 'server',//设置为服务器端分页
                    pagination: true, //是否分页
                    search: true, //显示搜索框
                    pageSize: 5,//每页的行数 
                    pageList: [5, 10, 20],
                    pageNumber: 1,//显示的页数
                    showRefresh: true,//刷新
                    striped: true,//条纹
                    sortName: 'adminID',
                    sortOrder: 'desc',

                });
        
  

    //删除按钮
    $("#BtnDel").click(function () {
        var DelNumS = getCheck();//获取选中行的人的编号
        //    alert(DelNumS);

        //判断是否为空。。前面是否有多余的 逗号.(如果是全选,前面会多个,)
        if (DelNumS.charAt(0) == ",") { DelNumS = DelNumS.substring(1); }

        if (DelNumS == "") { alert("请选择额要删除的数据"); }
        else
        {
            $.ajax({
                type: "post",
                url: "ashx/del.ashx",
                data: { "Action": "Del", "DelNums": DelNumS },
                dataType: "text",
                success: function (data) {
                    var json = eval('(' + data + ')');
                    alert(json.info);
                    //刷新页面
                 //  window.location.reload();
                  $('#table').bootstrapTable('refresh');
                }
            });

        }
    });
});



function SEXFormatter(value, row, index) { //处理性别的显示
    if (value == 'True') {
        value = '男';
    }
    else {
        value = '女';
    }
    return value;
}
function editFormatter(value, row, index) { //处理操作

    var str = '<a href="modify.aspx?id=' + value + '">编辑</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="show.html?UserID=' + value + '">详情</a>'
    value = str;
    return value;
}

function getCheck() { //获取表格里选中的行 的编号
    var data = [];//数组
    $("#table").find(":checkbox:checked").each(function () {
        var val = $(this).parent().next().text();//当前元素的上一级---里的下一个元素--的内容
        data.push(val);
    });
    return data.join(",");//用,连接
}
list2.js

3.写删除功能

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 
 6 namespace web.Admin.ashx
 7 {
 8     /// <summary>
 9     /// Del 的摘要说明
10     /// </summary>
11     public class Del : IHttpHandler
12     {
13 
14         public void ProcessRequest(HttpContext context)
15         {
16             context.Response.ContentType = "text/plain";
17             string json = "{}";
18             string action = context.Request.Form["Action"];
19             if (action == "Del")//删除操作
20             {
21                 string DelNumS = context.Request.Form["DelNumS"];//获取批量删除的编号
22                 BLL.Admin bll = new BLL.Admin();
23                 if (bll.DeleteList(DelNumS))
24                 {
25                     json = "{'info':'删除成功'}";
26                 }
27                 else
28                 { json = "{'info':'删除失败'}"; }
29             }
30             context.Response.Write(json);
31         }
32 
33         public bool IsReusable
34         {
35             get
36             {
37                 return false;
38             }
39         }
40     }
41 }
del.ashx

4.写获取数据列表

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Data;
 6 namespace web.Admin.ashx
 7 {
 8     /// <summary>
 9     /// l1 的摘要说明
10     /// </summary>
11     public class list2 : IHttpHandler, System.Web.SessionState.IRequiresSessionState//session接口
12     {
13 
14         public void ProcessRequest(HttpContext context)
15         {
16             context.Response.ContentType = "text/plain";
17             string json = "{}";
18             string action = context.Request.Form["Action"];
19 
20             int displayStart = int.Parse(context.Request["offset"]);
21             int displayLength = int.Parse(context.Request["limit"]);
22 
23             BLL.Admin bll = new BLL.Admin();
24             int total = bll.GetRecordCount("");
25                     DataSet ds = bll.GetListByPage("","", displayStart+1, displayStart+ displayLength);
26                     ds.Tables[0].TableName = "rows";
27                     //返回列表
28                     json = Web.DataConvertJson.DataTable2Json(ds.Tables[0]);
29             //http://down.admin5.com/info/2015/1209/130229.html
30             //??服务器端返回的数据中还要包括rows,total(数据总量)两个字段,前端要根据这两个字段分页。
31             json = "{\"total\":" + total + "," + json.Substring(1);
32 
33             /*
34              返回数据格式
35              {"total":100,"rows":....}
36              
37              */
38 
39             context.Response.Write(json);
40         }
41 
42         public bool IsReusable
43         {
44             get
45             {
46                 return false;
47             }
48         }
49     }
50 }
list.ashx

5.BLL代码(...摘了部分)

1     public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
2         {
3             return dal.GetListByPage( strWhere,  orderby,  startIndex,  endIndex);
4         }
关键代码

6.关键的数据访问层

public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
        {
            StringBuilder strSql=new StringBuilder();
            strSql.Append("SELECT * FROM ( ");
            strSql.Append(" SELECT ROW_NUMBER() OVER (");
            if (!string.IsNullOrEmpty(orderby.Trim()))
            {
                strSql.Append("order by T." + orderby );
            }
            else
            {
                strSql.Append("order by T.adminID desc");
            }
            strSql.Append(")AS Row, T.*  from Admin T ");
            if (!string.IsNullOrEmpty(strWhere.Trim()))
            {
                strSql.Append(" WHERE " + strWhere);
            }
            strSql.Append(" ) TT");
            strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
            return DbHelperSQL.Query(strSql.ToString());
        }
分页查询
 /// <summary>
        /// 批量删除数据
        /// </summary>
        public bool DeleteList(string adminIDlist )
        {
            StringBuilder strSql=new StringBuilder();
            strSql.Append("delete from Admin ");
            strSql.Append(" where adminID in ("+adminIDlist + ")  ");
            int rows=DbHelperSQL.ExecuteSql(strSql.ToString());
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
批量删除
        /// <summary>
        /// 获取记录总数
        /// </summary>
        public int GetRecordCount(string strWhere)
        {
            StringBuilder strSql=new StringBuilder();
            strSql.Append("select count(1) FROM Admin ");
            if(strWhere.Trim()!="")
            {
                strSql.Append(" where "+strWhere);
            }
            object obj = DbHelperSQL.GetSingle(strSql.ToString());
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
获取记录行数

7.admin类

 1 /**  版本信息模板在安装目录下,可自行修改。
 2 * Admin.cs
 3 *
 4 * 功 能: N/A
 5 * 类 名: Admin
 6 *
 7 * Ver    变更日期             负责人  变更内容
 8 * ───────────────────────────────────
 9 * V0.01  2016/3/1 16:02:52   N/A    初版
10 *
11 * Copyright (c) 2012 Maticsoft Corporation. All rights reserved.
12 *┌──────────────────────────────────┐
13 *│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │
14 *│ 版权所有:动软卓越(北京)科技有限公司              │
15 *└──────────────────────────────────┘
16 */
17 using System;
18 namespace Model
19 {
20     /// <summary>
21     /// Admin:实体类(属性说明自动提取数据库字段的描述信息)
22     /// </summary>
23     [Serializable]
24     public partial class Admin
25     {
26         public Admin()
27         {}
28         #region Model
29         private int _adminid;
30         private string _loginid;
31         private string _loginpwd;
32         private string _adminname;
33         private bool _sex;
34         /// <summary>
35         /// 
36         /// </summary>
37         public int adminID
38         {
39             set{ _adminid=value;}
40             get{return _adminid;}
41         }
42         /// <summary>
43         /// 
44         /// </summary>
45         public string LoginID
46         {
47             set{ _loginid=value;}
48             get{return _loginid;}
49         }
50         /// <summary>
51         /// 
52         /// </summary>
53         public string LoginPWD
54         {
55             set{ _loginpwd=value;}
56             get{return _loginpwd;}
57         }
58         /// <summary>
59         /// 
60         /// </summary>
61         public string AdminName
62         {
63             set{ _adminname=value;}
64             get{return _adminname;}
65         }
66         /// <summary>
67         /// 
68         /// </summary>
69         public bool sex
70         {
71             set{ _sex=value;}
72             get{return _sex;}
73         }
74         #endregion Model
75 
76     }
77 }
admin.cs

 

posted @ 2016-05-04 16:22  chenglingr  阅读(1128)  评论(1编辑  收藏  举报
生活在继续,我们需要活着