【转】Asp.net利用Ajax实现DataGrid无刷新分页
DataGrid功能强大,我们只用写几行代码就能够实现复杂的页面数据显示。数据多的时候免不了要分页显 示,DataGrid本身自带分页功能,但是当数据量少的时候很方便,当大数据量时,DataGrid得分页机制就不太好了。于是在网上找到了一种比较好 的利用存储过程实现分页机制(客户端想要第几页就取第几页数据,上十万级的数据查询也很快,数据量再多的时候就没试过了,等有时间把利用存储过程分页也写 在blog上)在工作中为了让客户用的更舒服点,也赶时髦,想利用Ajax来实现DataGrid无刷新分页。主要用RenderControl方法把DataGrid翻译成Html代码,然后用Web Service 返回。当然也可以用别的方法。
GenericAjaxWS.asmx.cs
CODE:
//GenericAjaxWS.asmx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.Configuration;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.IO;
namespace GenricAjaxWS
{
[WebService(Namespace="http://localhost/GenricAjaxWS/")]
public class GenricAjaxWS : System.Web.Services.WebService
{
SqlCon nec tion con;
SqlDataAdapter da;
SqlCommand cmd;
DataSet ds;
public GenricAjaxWS()
{
InitializeComponent();
con= new SqlConnection(ConfigurationSettings.AppSettings["Connect"]);
da=new SqlDataAdapter("",con);
cmd=new SqlCommand("",con);
ds=new DataSet("TahaSchema");
}
Component Designer generated code#region Component Designer generated code
//Required by the Web Services Designer
private IContainer components = null;
/**////
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
private void InitializeComponent()
{
}
/**////
/// Clean up any resources being used.
///
protected override void Dispose( bool disposing )
{
if(disposing && components != null)
{
components.Dispose();
}
base.Dispose(disposing);
}
#endregion
/**////
/// this function accepts TSql statment and returns dataset
///
[WebMethod]
public string getGrid(string sqlStr,int pageIndex)
{
da.SelectCommand.CommandText=sqlStr;
da=new SqlDataAdapter(sqlStr,con);
da.Fill(ds,"myTable");
DataGrid dataGrid = new DataGrid();
dataGrid.AutoGenerateColumns = true;
dataGrid.DataSource = ds.Tables["myTable"].DefaultView;
dataGrid.AllowPaging = true;
dataGrid.PageSize = 4;
dataGrid.PagerStyle.Visible = false;
dataGrid.CurrentPageIndex = pageIndex;
try
{
dataGrid.DataBind();
}
catch(Exception)
{
}
StringWriter wr = new StringWriter();
HtmlTextWriter writer = new HtmlTextWriter(wr);
dataGrid.RenderControl(writer);
string gridHtml = wr.ToString();
wr.Close();
writer.Close();
DropDownList ddl_Pager = new DropDownList();
ddl_Pager.Attributes.Add("onchange","goToPage(this.value)");
string pager="";
for(int i=0;i
{
ListItem lItem = new ListItem(i.ToString(),i.ToString());
ddl_Pager.Items.Add(lItem);
if(i==pageIndex)
{
pager += "[background-color:#ffdd11;width" +
":20px;align:center"">
"=""goToPage('"+i+"')"">"+i+"]";
}
else
{
pager += "[width:20px;align:center"">" +
"
"('"+i+"')"" >"+i+"]";
}
}
ddl_Pager.SelectedIndex = pageIndex;
wr = new StringWriter();
writer = new HtmlTextWriter(wr);
ddl_Pager.RenderControl(writer);
string pagerHtml = "
" value='<' onclick='goToPrevPage()'>";
pagerHtml += wr.ToString();
pagerHtml += "
" onclick='this.disabled=goToNextPage()'>";
wr.Close();
writer.Close();
return pager+pagerHtml+"
"+gridHtml;
}
}
}
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.Configuration;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.IO;
namespace GenricAjaxWS
{
[WebService(Namespace="http://localhost/GenricAjaxWS/")]
public class GenricAjaxWS : System.Web.Services.WebService
{
SqlCon nec tion con;
SqlDataAdapter da;
SqlCommand cmd;
DataSet ds;
public GenricAjaxWS()
{
InitializeComponent();
con= new SqlConnection(ConfigurationSettings.AppSettings["Connect"]);
da=new SqlDataAdapter("",con);
cmd=new SqlCommand("",con);
ds=new DataSet("TahaSchema");
}
Component Designer generated code#region Component Designer generated code
//Required by the Web Services Designer
private IContainer components = null;
/**////
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
private void InitializeComponent()
{
}
/**////
/// Clean up any resources being used.
///
protected override void Dispose( bool disposing )
{
if(disposing && components != null)
{
components.Dispose();
}
base.Dispose(disposing);
}
#endregion
/**////
/// this function accepts TSql statment and returns dataset
///
[WebMethod]
public string getGrid(string sqlStr,int pageIndex)
{
da.SelectCommand.CommandText=sqlStr;
da=new SqlDataAdapter(sqlStr,con);
da.Fill(ds,"myTable");
DataGrid dataGrid = new DataGrid();
dataGrid.AutoGenerateColumns = true;
dataGrid.DataSource = ds.Tables["myTable"].DefaultView;
dataGrid.AllowPaging = true;
dataGrid.PageSize = 4;
dataGrid.PagerStyle.Visible = false;
dataGrid.CurrentPageIndex = pageIndex;
try
{
dataGrid.DataBind();
}
catch(Exception)
{
}
StringWriter wr = new StringWriter();
HtmlTextWriter writer = new HtmlTextWriter(wr);
dataGrid.RenderControl(writer);
string gridHtml = wr.ToString();
wr.Close();
writer.Close();
DropDownList ddl_Pager = new DropDownList();
ddl_Pager.Attributes.Add("onchange","goToPage(this.value)");
string pager="";
for(int i=0;i
{
ListItem lItem = new ListItem(i.ToString(),i.ToString());
ddl_Pager.Items.Add(lItem);
if(i==pageIndex)
{
pager += "[background-color:#ffdd11;width" +
":20px;align:center"">
"=""goToPage('"+i+"')"">"+i+"]";
}
else
{
pager += "[width:20px;align:center"">" +
"
"('"+i+"')"" >"+i+"]";
}
}
ddl_Pager.SelectedIndex = pageIndex;
wr = new StringWriter();
writer = new HtmlTextWriter(wr);
ddl_Pager.RenderControl(writer);
string pagerHtml = "
" value='<' onclick='goToPrevPage()'>";
pagerHtml += wr.ToString();
pagerHtml += "
" onclick='this.disabled=goToNextPage()'>";
wr.Close();
writer.Close();
return pager+pagerHtml+"
"+gridHtml;
}
}
}
上面的是Web服务,然后利用Ajax请求这个服务来获取要现实的数据。以下是客户端JavaScript代码:
AjaxFuncs.js
CODE:
//声明异步请求对象
/////////////////////////////////////////////////////////////////
var xmlhttp;
/////////////////////////////////////////////////////////////////
//填充DataGrid,这个函数有3个参数。
//第一个是包含DataGrid的DIV的ID
//第二个是查询数据的sql语句
//第三个是要获取第几页数据
/////////////////////////////////////////////////////////////////
var ph;
var fil lG rid_Str_SQL="";
var currentPageIndex ;
function fil lG rid(myPH,str_Sql,pageIndex){
ph = window.document.getElementById(myPH);
fillGrid_Str_SQL = str_Sql;
currentPageIndex = pageIndex;
var url = "http://localhost/GenricAjaxWS/GenricAjaxWS" +
".asmx/getGrid?sqlStr="+str_Sql+
"&pageIndex="+pageIndex;
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=fillGrid_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
//code for IE
else if (window.ActiveXObject)
{
try
{
xmlhttp= new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){}
}
if(xmlhttp)
{
try
{
xmlhttp.onreadystatechange=fil lG rid_Change;
xmlhttp.open("GET",url,false);
xmlhttp.send();
}
catch(e){}
}
}
}
function fillGrid_Change()
{
if(xmlhttp.readyState==4&&xmlhttp.status==200)
{
//var rows=xmlhttp.respon seX ML.
// selectNodes(".//TahaSchema//TahaTable");
var row = xmlhttp.responseXML.selectNodes(".//");
ph.innerHTML = row[1].text;
}
}
function goToPage(pageIndex){
fil lG rid(ph.id,fillGrid_Str_SQL,pageIndex)
}
function goToNextPage(){
try{
fillGrid(ph.id,fillGrid_Str_SQL,
parseInt(currentPageIndex)+1);
return false;
}
catch(e){
return true;
}
}
function goToPrevPage(){
fil lG rid(ph.id,fillGrid_Str_SQL,
parseInt(currentPageIndex)-1)
}
/////////////////////////////////////////////////////////////////
var xmlhttp;
/////////////////////////////////////////////////////////////////
//填充DataGrid,这个函数有3个参数。
//第一个是包含DataGrid的DIV的ID
//第二个是查询数据的sql语句
//第三个是要获取第几页数据
/////////////////////////////////////////////////////////////////
var ph;
var fil lG rid_Str_SQL="";
var currentPageIndex ;
function fil lG rid(myPH,str_Sql,pageIndex){
ph = window.document.getElementById(myPH);
fillGrid_Str_SQL = str_Sql;
currentPageIndex = pageIndex;
var url = "http://localhost/GenricAjaxWS/GenricAjaxWS" +
".asmx/getGrid?sqlStr="+str_Sql+
"&pageIndex="+pageIndex;
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=fillGrid_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
//code for IE
else if (window.ActiveXObject)
{
try
{
xmlhttp= new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){}
}
if(xmlhttp)
{
try
{
xmlhttp.onreadystatechange=fil lG rid_Change;
xmlhttp.open("GET",url,false);
xmlhttp.send();
}
catch(e){}
}
}
}
function fillGrid_Change()
{
if(xmlhttp.readyState==4&&xmlhttp.status==200)
{
//var rows=xmlhttp.respon seX ML.
// selectNodes(".//TahaSchema//TahaTable");
var row = xmlhttp.responseXML.selectNodes(".//");
ph.innerHTML = row[1].text;
}
}
function goToPage(pageIndex){
fil lG rid(ph.id,fillGrid_Str_SQL,pageIndex)
}
function goToNextPage(){
try{
fillGrid(ph.id,fillGrid_Str_SQL,
parseInt(currentPageIndex)+1);
return false;
}
catch(e){
return true;
}
}
function goToPrevPage(){
fil lG rid(ph.id,fillGrid_Str_SQL,
parseInt(currentPageIndex)-1)
}
最后就是显示数据的html页面,实例代码如下:
AjaxGrid.html:
CODE:
<html>
<head>
<title>AjaxGrid</title>
<script language="javascript"
type="text/javascript" src="ajaxFuncs.js"></script>
</head>
<body onload="fil lG rid('myPH','select * from sales',1)">
<form id="Form1" method="post" runat="server">
<div id="myPH" ></div>
</form>
</body>
</html>
<head>
<title>AjaxGrid</title>
<script language="javascript"
type="text/javascript" src="ajaxFuncs.js"></script>
</head>
<body onload="fil lG rid('myPH','select * from sales',1)">
<form id="Form1" method="post" runat="server">
<div id="myPH" ></div>
</form>
</body>
</html>