这几天无意间看到一个关于分页的帖子,觉得写得挺好的。关于这些东西,自己一直都是只知道原理,却没有真正动手做过,于是研究了一下分页的原理自己动手写了一个十分特别非常简单的分页程序,在这里与大家分享一下。
这个程序取数据使用的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></param> /// <param></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>字符串</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 'https://www.jb51.net/': 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="https://www.jb51.net/Content/jquery/jquery-1.11.1.min.js"></script> <title></title> </head> <body> <table></table> <div> <a href="javascript:void(0);">首页</a> <a href="javascript:void(0);">上一页</a> <span>当前<input type="text" value="1" disabled="disabled" />页,总共<input type="text" value="" disabled="disabled" />条数据,共<input type="text" value="" disabled="disabled" />页</span> <a href="javascript:void(0);">下一页</a> <a href="javascript:void(0);">尾页</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>