项目中经常会用到分页的功能类似的项目做过无数个了,今个把自己常用的分页代码分享一下。
首先说说服务端处理的代码:
下面代码中重点是分页的sql语句的写法,其中的参数@n是当前的页码,总的来说本服务端主要向前台输出了2个值,接收了一个参数(当前页码),输出的是总的页数和当前页码下的数据。
sql = "select t.* from (select *,ROW_NUMBER() over(order by id asc) rownum from eazy_yiliaofuwu where typeid='"+id+"')t where t.rownum>=(@n-1)*10+1 and t.rownum<=@n*10";
DataTable dt = DbHelperSQL.Query(sql, new SqlParameter("@n", pagenum)).Tables[0];
namespace EazyCMS.Web.tools { /// <summary> /// getyaopinfuwu 的摘要说明 /// </summary> public class getyaopinfuwu : IHttpHandler { private string sql = string.Empty; private int total = 0; public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string id = context.Request["id"]; int pagenum = Convert.ToInt32(context.Request["pagenum"]); sql = "select t.* from (select *,ROW_NUMBER() over(order by id asc) rownum from eazy_yiliaofuwu where typeid='"+id+"')t where t.rownum>=(@n-1)*10+1 and t.rownum<=@n*10"; DataTable dt = DbHelperSQL.Query(sql, new SqlParameter("@n", pagenum)).Tables[0]; //这里得到的根据条件查询得到的数据总的条数 total = Convert.ToInt32(DbHelperSQL.GetSingle("select COUNT(*) from eazy_yiliaofuwu where typeid=" + id)); Medicalitems medicalitems = new Medicalitems(); medicalitems.medicalitem = new Medicalitem[dt.Rows.Count]; medicalitems.PageCount = (int)Math.Ceiling(total / 10.0);//总的页码0.1→1 , 0.95→1, 1.01→2,1.0→1 for (int i = 0; i < dt.Rows.Count; i++) { medicalitems.medicalitem[i] = new Medicalitem() { MedicalCode=dt.Rows[i]["ylcode"].ToString(), MedicalContent=dt.Rows[i]["itemcontent"].ToString(), MedicalName=dt.Rows[i]["itemname"].ToString(), MedicalPrice=dt.Rows[i]["price"].ToString(), MedicalUnit=dt.Rows[i]["danwei"].ToString() }; } context.Response.Write(new JavaScriptSerializer().Serialize(medicalitems)); } public bool IsReusable { get { return false; } } } class Medicalitems { public Medicalitem[] medicalitem { get; set; } public int PageCount { get; set; } } class Medicalitem { public string MedicalCode { get; set; } public string MedicalName { get; set; } public string MedicalContent { get; set; } public string MedicalUnit { get; set; } public string MedicalPrice { get; set; } } }