這篇文章主要介紹了C#基于數據庫存儲過程的AJAX分頁實現方法,以實例形式詳細講述了數據庫存儲過程的定義、數據庫的訪問及Ajax的實現技巧,需要的朋友可以參考下
本文實例講述了C#基于數據庫存儲過程的AJAX分頁實現方法。分享給大家供大家參考。具體如下:
首先我們在數據庫(SQL Server)中聲明定義存儲過程
復制代碼代碼如下:
use sales --指定數據庫
if(exists(select * from sys.objects where name='proc_location_Paging')) --如果這個proc_location_paging存儲過程存在則刪除
drop proc proc_location_Paging
go
create proc proc_location_Paging --創建存儲過程
(
@pageSize int, --頁大小
@currentpage int, --當前頁
@rowCount int output, --總行數(傳出參數)
@pageCount int output --總頁數(傳出參數)
)
as
begin
select @rowCount= COUNT(locid) from location --給@rowCount賦值
select @pageCount= CEILING((count(locid)+0.0)/@pageSize) from location --給@pageCount賦值
select top (@pagesize)* from (select ROW_NUMBER() over(order by locid) as rowID,* from location) as t1
where rowID >(@pageSize*(@currentpage-1))
end
go
---------------------------------以上就表示這個存儲過程已經定義完了。
---------------------------------以下是執行這個存儲過程。我們可以看結果
declare @rowCount int,@pageCount int --先聲明兩個參數
--執行proc_location_Paging這個存儲過程。@rowCount,@pageCount后面都有output 表示它們兩是輸出參數
exec proc_location_Paging 10,1,@rowCount output,@pageCount output
select @rowCount,@pageCount --查詢這兩個參數的值
因為是直接訪問數據庫的,所以我們將下面這條方法寫入到DAL層中,這里我將它寫入到SqlHelper中
復制代碼代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Reflection;
namespace LLSql.DAL
{
public class SqlHelper
{
/// <summary>
/// 獲取連接數據庫字符串
/// </summary>
private static string connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
public static DataTable ExecuteProcPageList(int pageSize, int currentPage, out int rowCount, out int pageCount)
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "proc_location_paging"; //存儲過程的名字
cmd.CommandType = CommandType.StoredProcedure; //設置命令為存儲過程類型(即:指明我們執行的是一個存儲過程)
rowCount = 0;
pageCount = 0;//這里隨便給rowCount,pageCount賦個值,因為使用out傳遞參數的時候,在方法內部一定要給out參數賦值才能用它,但是雖然這里給它賦初值了,但是在執行存儲過程中,存儲過程又會給這兩個參數賦值,并返還回來給我們,那個才是我們要值
SqlParameter[] parameters ={
new SqlParameter("@pageSize",pageSize),
new SqlParameter("@currentpage",currentPage),
new SqlParameter("@rowCount",rowCount),
new SqlParameter("@pageCount",pageCount)
};
//因為在存儲過程中@rowCount 與@pageCount 是一個輸出參數(output), 而parameters這個數組里,第三,和第四個參數就是要用來替換掉這兩個輸出參數的,所以這里要將parameters這個數組里的這兩個參數設為輸出參數。
parameters[2].Direction = ParameterDirection.Output;
parameters[3].Direction = ParameterDirection.Output;
cmd.Parameters.AddRange(parameters); //將參數傳遞給我們的cmd命令對象
DataTable dt = new DataTable();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(dt);//到數據庫去執行存儲過程,并將結果填充到dt表中
}
//等存儲過程執行完畢后,存儲過程會把這兩個輸出參數傳遞出來。那么我們在這里來取得這兩個返回參數。
rowCount = Convert.ToInt32(parameters[2].Value);
pageCount = Convert.ToInt32(parameters[3].Value);
return dt;
}
}
}
}
}
在DAL文件夾中( 層中) 創建一個Aticel.cs類 產生一個list
復制代碼代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using LLSql.DAL;
using WebApplication1.Model;
namespace WebApplication1.DAL
{
public class Aticel
{
public static List<Location> GetPageListByPageIndex(int pageSize,int currentpage,out int rowCount,out int pageCount)
{
DataTable dt= SqlHelper.ExecuteProcPageList(pageSize, currentpage,out rowCount,out pageCount);
var list = new List<Location>();// 聲明一個泛型對象list
if (dt != null && dt.Rows.Count > 0)
{
//將DataTable轉換成一個list
list = (from p in dt.AsEnumerable() //(遍歷DataTable)
select new Model.Location
{
Locid = p.Field<int>("locid"), //將DateTable里的字段賦值給Location類中的屬性
LocName = p.Field<string>("locName"),
ParentId = p.Field<int>("parentId"),
LocType = p.Field<short>("locType"),
ElongCode = p.Field<string>("elongCode"),
CityCode = p.Field<string>("CityCode"),
BaiduPos = p.Field<string>("BaiduPos"),
Versions = p.Field<short>("Version")
}).ToList();
}
return list; //將這個list返回回去
}
}
}
在API這個文件夾中創建一個GetPageData.ashx 頁 (BLL層) 在這里調用ADL層里的 Aticel.cs類中的GetPageListByPageIndex()方法,獲取一個list 并將這個list轉換成一個Json格式字符串, 共AJAX 異步請求得到。
復制代碼代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
namespace WebApplication1.API
{
/// <summary>
/// GetPageData 的摘要說明
/// </summary>
public class GetPageData : IHttpHandler
{
/// <summary>
/// 根據用戶傳遞的當前頁的頁碼來獲取數據
/// </summary>
/// <param name="context"></param>
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
int pageSize = 10; //設定頁大小,每頁顯示10條數據
int currentPage = Convert.ToInt32(context.Request.QueryString["currentPage"]); //設定當前頁
int rowCount = 0; //作為out參數傳遞給方法,在方法里給rowCount賦值
int pageCount = 0; //作為out參數傳遞給方法,在方法里給rowCount賦值
string jsonData = null;
List<Model.Location> list= DAL.Aticel.GetPageListByPageIndex(pageSize, currentPage, out rowCount, out pageCount);
if (list != null && list.Count > 0)
{
//創建Json序列化器,將對象轉換成一個Json格式的字符串
JavaScriptSerializer jsz = new JavaScriptSerializer();
jsonData = jsz.Serialize(list); //將一個list對象轉換成json格式的字符串
context.Response.Write(jsonData);
}
else
{
context.Response.Write("no");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
前端頁面 (將AJAX請求得到的數據展示也頁面)
復制代碼代碼如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>使用AJAX分頁</title>
<script src="jquery-1.11.2.js" type="text/javascript"></script>
<style type="text/css">
table{ margin:80px 500px; }
td{ width:50px; height:auto}
</style>
<script type="text/javascript">
$(function () {
$.get("API/GetPageData.ashx?currentPage=2", function (obj) { //假設當前頁是第二頁currentPage=2
//debugger;
var JsonData = $.parseJSON(obj);
//alert(JsonData[0].Locid);
//debugger;
for (var i = 0; i < JsonData.length; i++) {
var data = "<tr><td >" + JsonData[i].Locid + "</td><td >" + JsonData[i].LocName + "</td><td >" + JsonData[i].ParentId + "</td><td >" + JsonData[i].LocType + "</td><td >" + JsonData[i].ElongCode + "</td><td >" + JsonData[i].CityCode + "</td><td >" + JsonData[i].BaiduPos + "</td><td >" + JsonData[i].Versions + "</td></tr>";
$("#t1").append(data);
}
})
})
</script>
</head>
<body>
<table border="1" cellpadding="5" cellspacing="0" style="margin-top:100px;width:600px;" id="t1">
<tr><td>編號</td><td >城市名</td><td >父ID</td><td >locType</td><td >elongCode</td><td >CityCode</td><td >BaiduPos</td><td >Version</td></tr>
</table>
</body>
</html>
希望本文所述對大家的C#程序設計有所幫助。