这几天无意间看到一个关于分页的帖子,觉得写得挺好的。关于这些东西,自己一直都是只知道原理,却没有真正动手做过,于是研究了一下分页的原理自己动手写了一个十分特别非常简单的分页程序,在这里与大家分享一下。
这个程序取数据使用的ado.net,首先先新建一个取数据的类PageDAl
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Web;
namespace page.DAL { public class PageDal { public DataTable GetUserList(out int totalCount, int pageIndex = 1, int pagesize = 10) { using ( SqlConnection coon = new SqlConnection(ConfigurationManager.ConnectionStrings["userConnection"].ConnectionString)) { coon.Open(); string sqlCount = "select count(F_Id) from Sys_User"; SqlCommand cmd = new SqlCommand(sqlCount, coon); totalCount = int.Parse(cmd.ExecuteScalar().ToString()); string sql = "select F_Account,F_RealName from (select *,Row_Number() over(order by F_Account) r from Sys_User)as w where r>{0} and r<={1};"; SqlDataAdapter ad = new SqlDataAdapter(String.Format(sql, (pageIndex - 1) * pagesize, (pageIndex * pagesize)), coon); DataTable dt = new DataTable(); ad.Fill(dt); return dt; } } } }
然后记得修改一下webconfig里面的连接数据库的字符串,数据库自己随便建一个就行。
接下来是ashx一般处理程序,html页面把需求传过来,他在从PageDal中取数据。
using page.DAL; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Web; namespace page { /// <summary> /// WebHandler 的摘要说明 /// </summary> public class WebHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { try { int pageIndex = int.Parse(context.Request.Form["pageindex"]); int pageSize = int.Parse(context.Request.Form["pagesize"]); PageDal pd = new PageDal(); int totalCount; DataTable dt = pd.GetUserList(out totalCount, pageIndex, pageSize); string json = ToJson(dt, "data", totalCount); context.Response.ContentType = "text/plain"; context.Response.Write(json); } catch { context.Response.Write("error"); } } public bool IsReusable { get { return false; } } /// <summary> /// DataTable转换为Json /// </summary> public static string ToJson(DataTable dt, string jsonName, int count) { StringBuilder Json = new StringBuilder(); if (string.IsNullOrEmpty(jsonName)) jsonName = dt.TableName; Json.Append("{\"" + jsonName + "\":["); if (dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { Json.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { Type type = dt.Rows[i][j].GetType(); Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j].ToString(), type)); if (j < dt.Columns.Count - 1) { Json.Append(","); } } Json.Append("}"); if (i < dt.Rows.Count - 1) { Json.Append(","); } } } Json.Append("],"); Json.Append("\"count\":" + count + "}"); return Json.ToString(); } /// <summary> /// 格式化字符型、日期型、布尔型 /// </summary> /// <param name="str"></param> /// <param name="type"></param> /// <returns></returns> private static string StringFormat(string str, Type type) { if (type == typeof(string)) { str = String2Json(str); str = "\"" + str + "\""; } else if (type == typeof(DateTime)) { str = "\"" + str + "\""; } else if (type == typeof(bool)) { str = str.ToLower(); } else if (type != typeof(string) && string.IsNullOrEmpty(str)) { str = "\"" + str + "\""; } return str; } /// <summary> /// 过滤特殊字符 /// </summary> /// <param name="s">字符串</param> /// <returns>json字符串</returns> private static string String2Json(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.Length; i++) { char c = s.ToCharArray()[i]; switch (c) { case '\"': sb.Append("\\\""); break; case '\\': sb.Append("\\\\"); break; case '/': sb.Append("\\/"); break; case '\b': sb.Append("\\b"); break; case '\f': sb.Append("\\f"); break; case '\n': sb.Append("\\n"); break; case '\r': sb.Append("\\r"); break; case '\t': sb.Append("\\t"); break; default: sb.Append(c); break; } } return sb.ToString(); } } }
最后就是html代码了
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="../Content/jquery/jquery-1.11.1.min.js"></script> <title></title> </head> <body> <table id="datatable"></table> <div id="pageination" style="width: 100%"> <a href="javascript:void(0);" οnclick="GoFirst()">首页</a> <a href="javascript:void(0);" οnclick="GoPre()">上一页</a> <span>当前<input id="pageindex" type="text" style="width:20px" value="1" disabled="disabled" />页,总共<input id="totalcount" type="text" style="width:20px" value="" disabled="disabled" />条数据,共<input id="pagecount" type="text" style="width:20px" value="" disabled="disabled" />页</span> <a href="javascript:void(0);" οnclick="GoNext()">下一页</a> <a href="javascript:void(0);" οnclick="GoLast()">尾页</a> </div> </body> </html> <script> var pageindex = 1; var pagesize = 15; $(function () { search(); }); function search() { $.ajax({ url: "../WebHandler.ashx", type: "post", data: { "pagesize": pagesize, "pageindex": pageindex }, success: function (daa) { var json = JSON.parse(daa); var tab = $("#datatable"); tab.empty(); for (var i = 0; i < json.data.length ; i++) { tab.append("<tr><td>" + json.data[i].F_Account + "</td><td>" + json.data[i].F_RealName + "</td></tr>"); } var count = json.count; var pagecount = Math.ceil(count / pagesize); $("#totalcount").val(count); $("#pagecount").val(pagecount); } }); }; function GoFirst() { pageindex = 1; $("#pageindex").val(pageindex); search(); }; function GoLast() { var pageindex = $("#pagecount").val(); $("#pageindex").val(pageindex); search(); }; function GoPre() { if (pageindex > 1) { pageindex = pageindex - 1; $("#pageindex").val(pageindex); search(); } else { alert("这是第一页!"); } }; function GoNext() { var pagecount = $("#pagecount").val(); if (pageindex < pagecount) { pageindex = pageindex + 1; $("#pageindex").val(pageindex); search(); } else { alert("这是最后一页!"); } }; </script>
看完那篇帖子自己又对照的看了一下公司做的分页,总结了一下,以前都没认真想过关于分页的东西,觉得还挺难的,但经过一次总结发现其实只要你按顺序一点一点理清楚,有一个清晰的思路,完全不难的。
首先取数据,分两个部分,一个是把所有的数据个数统计出来另一个是取当前页码的数据,这个是很简单的,自己把有关的sql语句写好就行,sql语句的写法有很多,我取当前页码用的语句是
select F_Account,F_RealName from (select *,Row_Number() over(order by F_Account) r from Sys_User)as w where r> (pageIndex - 1) * pagesize and r<=pageIndex* pagesize
数据取出来之后就是把页面栏拼好,并且把相关的方法写好,比如说首页,前一页,下一页,尾页等,之后把数据总数传过来,计算页数就OK了。
<div id="pageination" style="width: 100%"> <a href="javascript:void(0);" onclick="GoFirst()">首页</a> <a href="javascript:void(0);" onclick="GoPre()">上一页</a> <span>当前<input id="pageindex" type="text" style="width:20px" value="1" disabled="disabled" />页,总共<input id="totalcount" type="text" style="width:20px" value="" disabled="disabled" />条数据,共<input id="pagecount" type="text" style="width:20px" value="" disabled="disabled" />页</span> <a href="javascript:void(0);" onclick="GoNext()">下一页</a> <a href="javascript:void(0);" onclick="GoLast()">尾页</a> </div> function GoFirst() { pageindex = 1; $("#pageindex").val(pageindex); search(); }; function GoLast() { var pageindex = $("#pagecount").val(); $("#pageindex").val(pageindex); search(); }; function GoPre() { if (pageindex > 1) { pageindex = pageindex - 1; $("#pageindex").val(pageindex); search(); } else { alert("这是第一页!"); } }; function GoNext() { var pagecount = $("#pagecount").val(); if (pageindex < pagecount) { pageindex = pageindex + 1; $("#pageindex").val(pageindex); search(); } else { alert("这是最后一页!"); } };