<%@ WebHandler Language="C#" Class="GetData" %> using System; using System.Web; using System.Data.SqlClient; using System.Data; using System.Collections.Generic; using System.Web.Script.Serialization; public class GetData : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; var pageIndex = context.Request["PageIndex"]; string connectionString = @"Data Source=KUSESQLEXPRESS;Initial Catalog=bookshop;Integrated Security=True"; //判斷當前索引存不存在,如果不存在則擷取記錄的總數。 if (string.IsNullOrEmpty(pageIndex)) { //擷取查詢記錄總數的sql語句 string sql = "select count(-1) from books"; int count = 0; int.TryParse(SqlHelper.ExecuteScalar(connectionString, System.Data.CommandType.Text, sql, null).ToString(), out count); context.Response.Write(count); context.Response.End(); } //當根據索引擷取資料 else { int currentPageIndex = 1; int.TryParse(pageIndex, out currentPageIndex); SqlParameter[] parms = new SqlParameter[] { new SqlParameter("@FEILDS",SqlDbType.NVarChar,1000), new SqlParameter("@PAGE_INDEX",SqlDbType.Int,10), new SqlParameter("@PAGE_SIZE",SqlDbType.Int,10), new SqlParameter("@ORDERTYPE",SqlDbType.Int,2), new SqlParameter("@ANDWHERE",SqlDbType.VarChar,1000), new SqlParameter("@ORDERFEILD",SqlDbType.VarChar,100) }; parms[0].Value = "*";//擷取所有的欄位 parms[1].Value = pageIndex;//當前頁面索引 parms[2].Value = 10;//頁面大小 parms[3].Value = 0;//升序排列 parms[4].Value = "";//條件陳述式 parms[5].Value = "ID";//排序欄位 List<Book> list = new List<Book>(); using (SqlDataReader sdr = SqlHelper.ExecuteReader(connectionString, CommandType.StoredProcedure, "PAGINATION", parms)) { while (sdr.Read()) { list.Add(new Book { Title = sdr[2].ToString(), Auhor = sdr[2].ToString(), PublishDate = sdr[4].ToString(), ISBN = sdr[5].ToString() }); } } context.Response.Write(new JavaScriptSerializer().Serialize(list).ToString());//轉為Json格式 } } public bool IsReusable { get { return false; } } } public class Book { public string Title { get; set; } public string Auhor { get; set; } public string PublishDate { get; set; } public string ISBN { get; set; } }
|