asp.net 无刷新翻页就是这么简单
程序员文章站
2024-03-08 20:35:22
个人喜欢用repeater,因其简洁,此ajaxpager定向为repeater! 一步一步看来: 代码 复制代码 代码如下: [defaultproperty("tota...
个人喜欢用repeater,因其简洁,此ajaxpager定向为repeater!
一步一步看来:
代码
[defaultproperty("totalrecord"),
toolboxdata("<{0}:ajaxpager runat=server></{0}:ajaxpager>")]
public class ajaxpager : webcontrol,icallbackeventhandler
{
public ajaxpager()
: base(htmltextwritertag.div)
{
this.load += new eventhandler(ajaxpager_load);
}
void ajaxpager_load(object sender, eventargs e)
{
string script = "function ajaxpagercallback(returndata){var parts =returndata.split('[_]'); document.getelementbyid('" + this.uniqueid.replace ('$','_') + "').innerhtml = parts[0];document.getelementbyid('" + info.containid + "').innerhtml=parts[1]}";
this.page.clientscript.registerclientscriptblock(this.page.gettype(), "ajaxpagercallback", script, true);
}
}
这里在load事件里向页面注册了一段js,ajaxpagercallback方法做两个操作,把自己表现的数据放入自己在客户端生成的div容器里,即id为this.uniqueid.replace('$','_')的div,clientid好像也可以!哈,一时糊涂!第二步就是把分页数据放到id为info.containid的div中,info对象下面会说到。
变量属性
#region 变量
private string _barbackgroundcolor = "#ffffff";
private string _barlinkcolor = "navy";
private string _barcurrentcolor = "#eeeeee";
private int _totalrecord = 50;
private int _totalpage = 0;
private int _currentindex = 1;
private int _itemsize = 10;
private pageinfo _info=new pageinfo ();
#endregion
#region 属性
#region 外观
[description("分页背景色"),
bindable(true),
category("外观"),
defaultvalue("#ffffff")]
public string barbackgroundcolor
{
get { return _barbackgroundcolor; }
set { _barbackgroundcolor = value; }
}
[description("分页条链接数字颜色"),
bindable(true),
category("外观"),
defaultvalue("navy")]
public string barlinkcolor
{
get { return _barlinkcolor; }
set { _barlinkcolor = value; }
}
[description("分页条当前页数字颜色"),
bindable(true),
category("外观"),
defaultvalue("#eeeeee")]
public string barcurrentcolor
{
get { return _barcurrentcolor; }
set { _barcurrentcolor = value; }
}
#endregion
#region 行为
[description("总记录数"),
category("行为"),
defaultvalue(50)]
public int totalrecord
{
get { return _totalrecord; }
set
{
_totalrecord = value;
}
}
[description("总页数"),
category("行为"),
defaultvalue(0)]
public int totalpage
{
get { return _totalpage; }
}
[description("bar的大小"),
category("行为"),
defaultvalue(10)]
public int barsize
{
get { return _itemsize; }
set
{
foreach (char c in system.convert.tostring(value))
{
if (!char.isnumber(c))
{
_itemsize = 10;
break;
}
}
_itemsize = value;
}
}
[description("当前页值"),
category("行为"),
defaultvalue(1)]
public int pageindex
{
get { return _currentindex; }
set { _currentindex = value; }
}
#endregion
public pageinfo info
{
get { return _info; }
set { _info = value; }
}
#endregion
这里自不必细说。其中的pageinfo如下:
pageinfo
[serializable]
public class pageinfo
{
private string _repeateruniqueid;
private string _containid="ajaxdata";
private string _tablename = string.empty;
private string _identityfield = "id";
private int _pagesize = 10;
private string _fields = "*";
private bool _isdesc = true;
private string _content = string.empty;
private string _connectstringname = string.empty;
public string repeateruniqueid
{
get { return _repeateruniqueid; }
set { _repeateruniqueid = value; }
}
public string containid
{
get { return _containid; }
set { _containid = value; }
}
public int pagesize
{
get { return _pagesize; }
set
{
_pagesize = int.parse(value.tostring());
}
}
public string tablename
{
get { return _tablename; }
set { _tablename = value; }
}
public string identityfield
{
get { return _identityfield; }
set { _identityfield = value; }
}
public string fields
{
get { return _fields; }
set { _fields = value; }
}
public bool isdesc
{
get { return _isdesc; }
set { _isdesc = value; }
}
public string content
{
get { return _content; }
set { _content = value; }
}
public string connectstringname
{
get { return _connectstringname; }
set { _connectstringname = value; }
}
}
这是标记为serializable,是因为下面要保存到viewstate里。
辅助方法
private string getcontents()
{
this._totalpage = ((this.totalrecord / this.info.pagesize) * this.info.pagesize == this.totalrecord) ? (this.totalrecord / this.info.pagesize) : ((this.totalrecord / this.info.pagesize) + 1);
int beginrecord = (this.pageindex - 1) * this.info.pagesize + 1;
int endrecord = math.min(this.pageindex * this.info.pagesize, this.totalrecord);
string pageinfo = string.format("[每页<span style='color:#cc0000'>{0}({1}-{2})</span>条 共<span style='color:#cc0000'>{3}</span>条<span style='color:#cc0000'>{4}</span>页]", info.pagesize, beginrecord, endrecord, this.totalrecord, this.totalpage);
stringbuilder pageliststr = new stringbuilder();
string pageindexcolor = "#000000";
int singlenumber = this.totalpage - (totalpage / barsize) * barsize;
int intpageformax = (this.pageindex - 1) / barsize;
int minint = (1 + barsize * intpageformax);
int maxint = ((intpageformax + 1) * barsize) > totalpage ? totalpage : ((intpageformax + 1) * barsize);
if (this.totalrecord == 0 || this.totalpage == 0)
{
pageliststr.appendformat("<span style='color:'{0};margin:auto 3px;'>0</span>", pageindexcolor);
pageliststr.appendformat(" [共<span style='color:#cc0000'>0</span>页/当前第<span style='color:#cc0000'>0</span>页 共<span style='color:#cc0000'>0</span>条记录,当前记录数<span style='color:#cc0000'>0</span>到<span style='color:#cc0000'>0</span>]");
return pageliststr.tostring();
}
else
{
if (this.totalpage <= this.barsize)
{
for (int i = 1; i <= totalpage; i++)
{
pageindexcolor = pageindex == i ? "#cc0000" : "#000000";
if (pageindex == i)
pageliststr.appendformat("<a id='{0}' style='color:{1};margin:auto 3px;'>{2}</a>", this.uniqueid, pageindexcolor, i);
else
pageliststr.appendformat("<a id='{0}' style='color:{1};margin:auto 3px;' href=\"javascript:{2}\">{3}</a>", this.uniqueid, pageindexcolor, page.clientscript.getcallbackeventreference(this, i.tostring(),"ajaxpagercallback",null), i);
}
pageliststr.appendformat(" {0}", pageinfo);
return pageliststr.tostring();
}
else
{
for (int i = minint; i <= maxint; i++)
{
pageindexcolor = pageindex == i ? "#cc0000" : "#000000";
if (pageindex == i)
pageliststr.appendformat("<a id={0}' style='color:{1};margin:auto 3px;'>{2}</a>", this.uniqueid, pageindexcolor, i);
else
pageliststr.appendformat("<a id='{0}' style='color:{1};margin:auto 3px;' href=\"javascript:{2}\">{3}</a>", this.uniqueid, pageindexcolor, page.clientscript.getcallbackeventreference(this, i.tostring(), "ajaxpagercallback", null), i);
}
if (pageindex <= barsize && totalpage > barsize)
{
pageliststr.appendformat("<a id='{0}' href=\"javascript:{1}\">下一页</a>", this.uniqueid, page.clientscript.getcallbackeventreference(this, system.convert.tostring(barsize + 1), "ajaxpagercallback", null));
}
if (this.pageindex > barsize && (totalpage - this.pageindex) >= singlenumber)
{
int multiminpageindex = (intpageformax * barsize);
int multimaxpageindex = ((intpageformax + 1) * barsize) + 1;
pageliststr.insert(0, string.format("<a id='{0}' href=\"javascript:{1}\">上一页</a>", this.uniqueid, page.clientscript.getcallbackeventreference(this, multiminpageindex.tostring(),"ajaxpagercallback",null)));
pageliststr.appendformat("<a id='{0}' href=\"javascript:{1}\">下一页</a>", this.uniqueid, page.clientscript.getcallbackeventreference(this, multimaxpageindex.tostring(),"ajaxpagercallback",null));
}
if (pageindex > 10 && (totalpage - pageindex) < singlenumber)
{
int multiminpageindex = (intpageformax * barsize);
pageliststr.insert(0, string.format("<a id='{0}' href=\"javascript:{1}\">上一页</a>", this.uniqueid, page.clientscript.getcallbackeventreference(this, multiminpageindex.tostring(), "ajaxpagercallback", null)));
}
pageliststr.appendformat(" {0}", pageinfo);
return pageliststr.tostring();
}
}
}
public void binddata()
{
repeater rpt = getrpt();
rpt.visible = true;
sqlhelper helper;
helper = this.info.connectstringname.isnullorempty() ? new sqlhelper() : new sqlhelper(info.connectstringname);
if (this.info.repeateruniqueid.isnullorempty())
{
throw new exception("必须给info的repeateruniqueid属性赋值");
}
int count = 0;
datatable dt = helper.getpagedata(info.tablename, info.fields, info.identityfield, info.pagesize, pageindex, info.isdesc, info.content, out count);
this.totalrecord = count;
rpt.datashow(dt);
}
private repeater getrpt()
{
return this.page.findcontrol(this.info.repeateruniqueid) as repeater;
}
先感谢一下写那个pager的人,getcontents(得到自己分页后的html)里我只做了少许改动,要不然还得细细算来!!
binddata(用到了我的sqlhelper)是利用为服务器的databind()方法把数据放到repeater里,只是不让它呈示,嘿嘿!
getrpt只是找到repeater引用
维护视图状态
#region 维护视图状态
protected override void loadviewstate(object savedstate)
{
triplet tp = savedstate as triplet;
this.totalrecord = convert.toint32(tp.third);
this.info = tp.second as pageinfo;
base.loadviewstate(tp.first);
}
protected override object saveviewstate()
{
triplet tp = new triplet();
tp.first = base.saveviewstate();
tp.second = info;
tp.third = this.totalrecord;
return tp;
}
#endregion
这里也不必说,只是pageinfo一定要能serializable。
重写方法
#region 重写方法
protected override void rendercontents(htmltextwriter writer)
{
writer.write(getcontents());
base.rendercontents(writer);
}
protected override void addattributestorender(htmltextwriter writer)
{
writer.addstyleattribute("white-space", "nowrap");
writer.addstyleattribute("padding-top", "2px");
writer.addstyleattribute("padding-bottom", "2px");
writer.addstyleattribute("color", "#949494");
writer.addstyleattribute("font-weight", "bold");
writer.addstyleattribute("background-color", this.barbackgroundcolor);
base.addattributestorender(writer);
}
#endregion
也不用说,大家一看都明白。
实现icallbackeventhandler
#region icallbackeventhandler 成员
public string getcallbackresult()
{
stringbuilder sb=new stringbuilder ();
stringwriter sw=new stringwriter (sb);
getrpt().rendercontrol(new htmltextwriter(sw));
return this.getcontents() + "[_]" + sb.tostring();
}
public void raisecallbackevent(string eventargument)
{
int pageindex = int.parse(eventargument);
this._currentindex = pageindex;
binddata();
}
#endregion
回调时先执行raisecallbackevent,所以currentindex改变了, binddata()执行了!!!!
返回时时执行getcallbackresult,string用"[_]"分开,对应上面注册的ajaxpagercallback js方法中的var parts =returndata.split('[_]');
ok!简单的ajax分页就这样简单的完成了!!!
northwind orders表调用如下:
页面中repeater包含在<div id="ajaxdata"></div>中
代码
private void bindpage(string content)
{
sinohelper.pageinfo info = new sinohelper.pageinfo();
info.pagesize = 5;
info.repeateruniqueid = rpt.uniqueid;
info.tablename = "orders";
info.fields = "orderid,customerid,shipcity";
info.identityfield = "orderid";
info.content = content;
ajaxpager1.info = info;
ajaxpager1.binddata();
}
附下载:
asp.net无刷新分页
一步一步看来:
代码
复制代码 代码如下:
[defaultproperty("totalrecord"),
toolboxdata("<{0}:ajaxpager runat=server></{0}:ajaxpager>")]
public class ajaxpager : webcontrol,icallbackeventhandler
{
public ajaxpager()
: base(htmltextwritertag.div)
{
this.load += new eventhandler(ajaxpager_load);
}
void ajaxpager_load(object sender, eventargs e)
{
string script = "function ajaxpagercallback(returndata){var parts =returndata.split('[_]'); document.getelementbyid('" + this.uniqueid.replace ('$','_') + "').innerhtml = parts[0];document.getelementbyid('" + info.containid + "').innerhtml=parts[1]}";
this.page.clientscript.registerclientscriptblock(this.page.gettype(), "ajaxpagercallback", script, true);
}
}
这里在load事件里向页面注册了一段js,ajaxpagercallback方法做两个操作,把自己表现的数据放入自己在客户端生成的div容器里,即id为this.uniqueid.replace('$','_')的div,clientid好像也可以!哈,一时糊涂!第二步就是把分页数据放到id为info.containid的div中,info对象下面会说到。
变量属性
复制代码 代码如下:
#region 变量
private string _barbackgroundcolor = "#ffffff";
private string _barlinkcolor = "navy";
private string _barcurrentcolor = "#eeeeee";
private int _totalrecord = 50;
private int _totalpage = 0;
private int _currentindex = 1;
private int _itemsize = 10;
private pageinfo _info=new pageinfo ();
#endregion
#region 属性
#region 外观
[description("分页背景色"),
bindable(true),
category("外观"),
defaultvalue("#ffffff")]
public string barbackgroundcolor
{
get { return _barbackgroundcolor; }
set { _barbackgroundcolor = value; }
}
[description("分页条链接数字颜色"),
bindable(true),
category("外观"),
defaultvalue("navy")]
public string barlinkcolor
{
get { return _barlinkcolor; }
set { _barlinkcolor = value; }
}
[description("分页条当前页数字颜色"),
bindable(true),
category("外观"),
defaultvalue("#eeeeee")]
public string barcurrentcolor
{
get { return _barcurrentcolor; }
set { _barcurrentcolor = value; }
}
#endregion
#region 行为
[description("总记录数"),
category("行为"),
defaultvalue(50)]
public int totalrecord
{
get { return _totalrecord; }
set
{
_totalrecord = value;
}
}
[description("总页数"),
category("行为"),
defaultvalue(0)]
public int totalpage
{
get { return _totalpage; }
}
[description("bar的大小"),
category("行为"),
defaultvalue(10)]
public int barsize
{
get { return _itemsize; }
set
{
foreach (char c in system.convert.tostring(value))
{
if (!char.isnumber(c))
{
_itemsize = 10;
break;
}
}
_itemsize = value;
}
}
[description("当前页值"),
category("行为"),
defaultvalue(1)]
public int pageindex
{
get { return _currentindex; }
set { _currentindex = value; }
}
#endregion
public pageinfo info
{
get { return _info; }
set { _info = value; }
}
#endregion
这里自不必细说。其中的pageinfo如下:
pageinfo
复制代码 代码如下:
[serializable]
public class pageinfo
{
private string _repeateruniqueid;
private string _containid="ajaxdata";
private string _tablename = string.empty;
private string _identityfield = "id";
private int _pagesize = 10;
private string _fields = "*";
private bool _isdesc = true;
private string _content = string.empty;
private string _connectstringname = string.empty;
public string repeateruniqueid
{
get { return _repeateruniqueid; }
set { _repeateruniqueid = value; }
}
public string containid
{
get { return _containid; }
set { _containid = value; }
}
public int pagesize
{
get { return _pagesize; }
set
{
_pagesize = int.parse(value.tostring());
}
}
public string tablename
{
get { return _tablename; }
set { _tablename = value; }
}
public string identityfield
{
get { return _identityfield; }
set { _identityfield = value; }
}
public string fields
{
get { return _fields; }
set { _fields = value; }
}
public bool isdesc
{
get { return _isdesc; }
set { _isdesc = value; }
}
public string content
{
get { return _content; }
set { _content = value; }
}
public string connectstringname
{
get { return _connectstringname; }
set { _connectstringname = value; }
}
}
这是标记为serializable,是因为下面要保存到viewstate里。
辅助方法
复制代码 代码如下:
private string getcontents()
{
this._totalpage = ((this.totalrecord / this.info.pagesize) * this.info.pagesize == this.totalrecord) ? (this.totalrecord / this.info.pagesize) : ((this.totalrecord / this.info.pagesize) + 1);
int beginrecord = (this.pageindex - 1) * this.info.pagesize + 1;
int endrecord = math.min(this.pageindex * this.info.pagesize, this.totalrecord);
string pageinfo = string.format("[每页<span style='color:#cc0000'>{0}({1}-{2})</span>条 共<span style='color:#cc0000'>{3}</span>条<span style='color:#cc0000'>{4}</span>页]", info.pagesize, beginrecord, endrecord, this.totalrecord, this.totalpage);
stringbuilder pageliststr = new stringbuilder();
string pageindexcolor = "#000000";
int singlenumber = this.totalpage - (totalpage / barsize) * barsize;
int intpageformax = (this.pageindex - 1) / barsize;
int minint = (1 + barsize * intpageformax);
int maxint = ((intpageformax + 1) * barsize) > totalpage ? totalpage : ((intpageformax + 1) * barsize);
if (this.totalrecord == 0 || this.totalpage == 0)
{
pageliststr.appendformat("<span style='color:'{0};margin:auto 3px;'>0</span>", pageindexcolor);
pageliststr.appendformat(" [共<span style='color:#cc0000'>0</span>页/当前第<span style='color:#cc0000'>0</span>页 共<span style='color:#cc0000'>0</span>条记录,当前记录数<span style='color:#cc0000'>0</span>到<span style='color:#cc0000'>0</span>]");
return pageliststr.tostring();
}
else
{
if (this.totalpage <= this.barsize)
{
for (int i = 1; i <= totalpage; i++)
{
pageindexcolor = pageindex == i ? "#cc0000" : "#000000";
if (pageindex == i)
pageliststr.appendformat("<a id='{0}' style='color:{1};margin:auto 3px;'>{2}</a>", this.uniqueid, pageindexcolor, i);
else
pageliststr.appendformat("<a id='{0}' style='color:{1};margin:auto 3px;' href=\"javascript:{2}\">{3}</a>", this.uniqueid, pageindexcolor, page.clientscript.getcallbackeventreference(this, i.tostring(),"ajaxpagercallback",null), i);
}
pageliststr.appendformat(" {0}", pageinfo);
return pageliststr.tostring();
}
else
{
for (int i = minint; i <= maxint; i++)
{
pageindexcolor = pageindex == i ? "#cc0000" : "#000000";
if (pageindex == i)
pageliststr.appendformat("<a id={0}' style='color:{1};margin:auto 3px;'>{2}</a>", this.uniqueid, pageindexcolor, i);
else
pageliststr.appendformat("<a id='{0}' style='color:{1};margin:auto 3px;' href=\"javascript:{2}\">{3}</a>", this.uniqueid, pageindexcolor, page.clientscript.getcallbackeventreference(this, i.tostring(), "ajaxpagercallback", null), i);
}
if (pageindex <= barsize && totalpage > barsize)
{
pageliststr.appendformat("<a id='{0}' href=\"javascript:{1}\">下一页</a>", this.uniqueid, page.clientscript.getcallbackeventreference(this, system.convert.tostring(barsize + 1), "ajaxpagercallback", null));
}
if (this.pageindex > barsize && (totalpage - this.pageindex) >= singlenumber)
{
int multiminpageindex = (intpageformax * barsize);
int multimaxpageindex = ((intpageformax + 1) * barsize) + 1;
pageliststr.insert(0, string.format("<a id='{0}' href=\"javascript:{1}\">上一页</a>", this.uniqueid, page.clientscript.getcallbackeventreference(this, multiminpageindex.tostring(),"ajaxpagercallback",null)));
pageliststr.appendformat("<a id='{0}' href=\"javascript:{1}\">下一页</a>", this.uniqueid, page.clientscript.getcallbackeventreference(this, multimaxpageindex.tostring(),"ajaxpagercallback",null));
}
if (pageindex > 10 && (totalpage - pageindex) < singlenumber)
{
int multiminpageindex = (intpageformax * barsize);
pageliststr.insert(0, string.format("<a id='{0}' href=\"javascript:{1}\">上一页</a>", this.uniqueid, page.clientscript.getcallbackeventreference(this, multiminpageindex.tostring(), "ajaxpagercallback", null)));
}
pageliststr.appendformat(" {0}", pageinfo);
return pageliststr.tostring();
}
}
}
public void binddata()
{
repeater rpt = getrpt();
rpt.visible = true;
sqlhelper helper;
helper = this.info.connectstringname.isnullorempty() ? new sqlhelper() : new sqlhelper(info.connectstringname);
if (this.info.repeateruniqueid.isnullorempty())
{
throw new exception("必须给info的repeateruniqueid属性赋值");
}
int count = 0;
datatable dt = helper.getpagedata(info.tablename, info.fields, info.identityfield, info.pagesize, pageindex, info.isdesc, info.content, out count);
this.totalrecord = count;
rpt.datashow(dt);
}
private repeater getrpt()
{
return this.page.findcontrol(this.info.repeateruniqueid) as repeater;
}
先感谢一下写那个pager的人,getcontents(得到自己分页后的html)里我只做了少许改动,要不然还得细细算来!!
binddata(用到了我的sqlhelper)是利用为服务器的databind()方法把数据放到repeater里,只是不让它呈示,嘿嘿!
getrpt只是找到repeater引用
维护视图状态
复制代码 代码如下:
#region 维护视图状态
protected override void loadviewstate(object savedstate)
{
triplet tp = savedstate as triplet;
this.totalrecord = convert.toint32(tp.third);
this.info = tp.second as pageinfo;
base.loadviewstate(tp.first);
}
protected override object saveviewstate()
{
triplet tp = new triplet();
tp.first = base.saveviewstate();
tp.second = info;
tp.third = this.totalrecord;
return tp;
}
#endregion
这里也不必说,只是pageinfo一定要能serializable。
重写方法
复制代码 代码如下:
#region 重写方法
protected override void rendercontents(htmltextwriter writer)
{
writer.write(getcontents());
base.rendercontents(writer);
}
protected override void addattributestorender(htmltextwriter writer)
{
writer.addstyleattribute("white-space", "nowrap");
writer.addstyleattribute("padding-top", "2px");
writer.addstyleattribute("padding-bottom", "2px");
writer.addstyleattribute("color", "#949494");
writer.addstyleattribute("font-weight", "bold");
writer.addstyleattribute("background-color", this.barbackgroundcolor);
base.addattributestorender(writer);
}
#endregion
也不用说,大家一看都明白。
实现icallbackeventhandler
复制代码 代码如下:
#region icallbackeventhandler 成员
public string getcallbackresult()
{
stringbuilder sb=new stringbuilder ();
stringwriter sw=new stringwriter (sb);
getrpt().rendercontrol(new htmltextwriter(sw));
return this.getcontents() + "[_]" + sb.tostring();
}
public void raisecallbackevent(string eventargument)
{
int pageindex = int.parse(eventargument);
this._currentindex = pageindex;
binddata();
}
#endregion
回调时先执行raisecallbackevent,所以currentindex改变了, binddata()执行了!!!!
返回时时执行getcallbackresult,string用"[_]"分开,对应上面注册的ajaxpagercallback js方法中的var parts =returndata.split('[_]');
ok!简单的ajax分页就这样简单的完成了!!!
northwind orders表调用如下:
页面中repeater包含在<div id="ajaxdata"></div>中
代码
复制代码 代码如下:
private void bindpage(string content)
{
sinohelper.pageinfo info = new sinohelper.pageinfo();
info.pagesize = 5;
info.repeateruniqueid = rpt.uniqueid;
info.tablename = "orders";
info.fields = "orderid,customerid,shipcity";
info.identityfield = "orderid";
info.content = content;
ajaxpager1.info = info;
ajaxpager1.binddata();
}
附下载:
asp.net无刷新分页