這幾天無意間看到一個關於分頁的帖子,覺得寫得挺好的。關於這些東西,自己一直都是只知道原理,卻沒有真正動手做過,於是研究了一下分頁的原理自己動手寫了一個十分特別非常簡單的分頁程序,在這裡與大家分享一下。
這個程序取數據使用的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);" 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> </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("這是最後一頁!"); } };
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。