zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C#基于数据库存储过程的AJAX分页实例

c#实例数据库存储AJAX 基于 过程 分页
2023-06-13 09:15:41 时间

本文实例讲述了C#基于数据库存储过程的AJAX分页实现方法。分享给大家供大家参考。具体如下:

首先我们在数据库(SQLServer)中声明定义存储过程

复制代码代码如下:
usesales   --指定数据库 
 
if(exists(select*fromsys.objectswherename="proc_location_Paging"))--如果这个proc_location_paging存储过程存在则删除 
dropprocproc_location_Paging 
go 
 
createprocproc_location_Paging  --创建存储过程 

@pageSizeint, --页大小 
@currentpageint, --当前页 
@rowCountintoutput, --总行数(传出参数) 
@pageCountintoutput --总页数(传出参数) 

as 
begin 
 
select@rowCount=COUNT(locid)fromlocation --给@rowCount赋值 
 
select@pageCount=CEILING((count(locid)+0.0)/@pageSize)fromlocation --给@pageCount赋值 
 
selecttop(@pagesize)*from(selectROW_NUMBER()over(orderbylocid)asrowID,*fromlocation)ast1 
whererowID>(@pageSize*(@currentpage-1)) 
 
end 
go 
---------------------------------以上就表示这个存储过程已经定义完了。 
 
---------------------------------以下是执行这个存储过程。我们可以看结果 
 
declare@rowCountint,@pageCountint --先声明两个参数 
 
--执行proc_location_Paging这个存储过程。@rowCount,@pageCount后面都有output表示它们两是输出参数 
execproc_location_Paging10,1,@rowCountoutput,@pageCountoutput   
 
select@rowCount,@pageCount --查询这两个参数的值

因为是直接访问数据库的,所以我们将下面这条方法写入到DAL层中,这里我将它写入到SqlHelper中

复制代码代码如下:
usingSystem; 
usingSystem.Collections.Generic; 
usingSystem.Linq; 
usingSystem.Text; 
usingSystem.Configuration; 
usingSystem.Data.SqlClient; 
usingSystem.Data; 
usingSystem.Reflection; 
 
namespaceLLSql.DAL 

   publicclassSqlHelper 
   { 
       ///<summary> 
       ///获取连接数据库字符串 
       ///</summary> 
       privatestaticstringconnStr=ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString; 
       publicstaticDataTableExecuteProcPageList(intpageSize,intcurrentPage,outintrowCount,outintpageCount) 
       { 
           using(SqlConnectionconn=newSqlConnection(connStr)) 
           { 
               conn.Open(); 
               using(SqlCommandcmd=conn.CreateCommand()) 
               { 
                   cmd.CommandText="proc_location_paging";//存储过程的名字 
                   cmd.CommandType=CommandType.StoredProcedure;//设置命令为存储过程类型(即:指明我们执行的是一个存储过程)
                   rowCount=0; 
                   pageCount=0;//这里随便给rowCount,pageCount赋个值,因为使用out传递参数的时候,在方法内部一定要给out参数赋值才能用它,但是虽然这里给它赋初值了,但是在执行存储过程中,存储过程又会给这两个参数赋值,并返还回来给我们,那个才是我们要值 
                   SqlParameter[]parameters={ 
                            newSqlParameter("@pageSize",pageSize), 
                            newSqlParameter("@currentpage",currentPage), 
                            newSqlParameter("@rowCount",rowCount), 
                            newSqlParameter("@pageCount",pageCount) 
                   }; 
                   //因为在存储过程中@rowCount与@pageCount是一个输出参数(output),而parameters这个数组里,第三,和第四个参数就是要用来替换掉这两个输出参数的,所以这里要将parameters这个数组里的这两个参数设为输出参数。 
                   parameters[2].Direction=ParameterDirection.Output;
                   parameters[3].Direction=ParameterDirection.Output;
                   cmd.Parameters.AddRange(parameters);//将参数传递给我们的cmd命令对象 

                   DataTabledt=newDataTable(); 
                   using(SqlDataAdapteradapter=newSqlDataAdapter(cmd)) 
                   { 
                       adapter.Fill(dt);//到数据库去执行存储过程,并将结果填充到dt表中 
                   } 
                   //等存储过程执行完毕后,存储过程会把这两个输出参数传递出来。那么我们在这里来取得这两个返回参数。 
                   rowCount=Convert.ToInt32(parameters[2].Value); 
                   pageCount=Convert.ToInt32(parameters[3].Value); 
                   returndt; 
               } 
           } 
       } 
   } 
}

在DAL文件夹中(层中)创建一个Aticel.cs类 产生一个list

复制代码代码如下:usingSystem; 
usingSystem.Collections.Generic; 
usingSystem.Linq; 
usingSystem.Web; 
usingSystem.Data; 
usingLLSql.DAL; 
usingWebApplication1.Model; 

namespaceWebApplication1.DAL 

   publicclassAticel 
   { 
       publicstaticList<Location>GetPageListByPageIndex(intpageSize,intcurrentpage,outintrowCount,outintpageCount) 
       { 
           DataTabledt=SqlHelper.ExecuteProcPageList(pageSize,currentpage,outrowCount,outpageCount); 
           varlist=newList<Location>();//声明一个泛型对象list 
           if(dt!=null&&dt.Rows.Count>0) 
           { 
               //将DataTable转换成一个list 
               list=(frompindt.AsEnumerable() //(遍历DataTable)
                       selectnewModel.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();  
           } 
           returnlist;//将这个list返回回去 
       } 
   } 
}

在API这个文件夹中创建一个GetPageData.ashx页(BLL层)在这里调用ADL层里的Aticel.cs类中的GetPageListByPageIndex()方法,获取一个list 并将这个list转换成一个Json格式字符串,共AJAX异步请求得到。

复制代码代码如下:usingSystem; 
usingSystem.Collections.Generic; 
usingSystem.Linq; 
usingSystem.Web; 
usingSystem.Web.Script.Serialization; 
 
namespaceWebApplication1.API 

   ///<summary> 
   ///GetPageData的摘要说明 
   ///</summary> 
   publicclassGetPageData:IHttpHandler 
   { 
       ///<summary> 
       ///根据用户传递的当前页的页码来获取数据 
       ///</summary> 
       ///<paramname="context"></param> 
       publicvoidProcessRequest(HttpContextcontext) 
       { 
           context.Response.ContentType="text/plain"; 
           intpageSize=10;//设定页大小,每页显示10条数据 
           intcurrentPage=Convert.ToInt32(context.Request.QueryString["currentPage"]);//设定当前页 
           introwCount=0; //作为out参数传递给方法,在方法里给rowCount赋值 
           intpageCount=0;//作为out参数传递给方法,在方法里给rowCount赋值 
           stringjsonData=null;  
           List<Model.Location>list=DAL.Aticel.GetPageListByPageIndex(pageSize,currentPage,outrowCount,outpageCount); 
           if(list!=null&&list.Count>0) 
           { 
               //创建Json序列化器,将对象转换成一个Json格式的字符串 
               JavaScriptSerializerjsz=newJavaScriptSerializer(); 
               jsonData=jsz.Serialize(list);//将一个list对象转换成json格式的字符串 
               context.Response.Write(jsonData); 
           } 
           else 
           { 
               context.Response.Write("no"); 
           } 
       } 
       publicboolIsReusable 
       { 
           get 
           { 
               returnfalse; 
           } 
       } 
   } 
}

前端页面 (将AJAX请求得到的数据展示也页面)

复制代码代码如下:<%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="WebForm1.aspx.cs"Inherits="WebApplication1.WebForm1"%> 
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<htmlxmlns="http://www.w3.org/1999/xhtml"> 
<headrunat="server"> 
   <title>使用AJAX分页</title> 
   <scriptsrc="jquery-1.11.2.js"type="text/javascript"></script> 
   <styletype="text/css"> 
     table{margin:80px500px;} 
     td{width:50px;height:auto} 
   </style> 
   <scripttype="text/javascript"> 
       $(function(){ 
           $.get("API/GetPageData.ashx?currentPage=2",function(obj){//假设当前页是第二页currentPage=2 
               //debugger; 
 
               varJsonData=$.parseJSON(obj); 
               //alert(JsonData[0].Locid); 
               //debugger; 
               for(vari=0;i<JsonData.length;i++){ 
                   vardata="<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> 
 <tableborder="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#程序设计有所帮助。