一个Asp.Net的显示分页方法 附加实体转换和存储过程 带源码下载
程序员文章站
2024-03-06 19:46:38
之前自己一直用aspnetpager控件来显示项目中的分页,但是每次都要拖一个aspnetpager的控件进去,感觉很不舒服,因为现在自己写的webform都不用服务器控件...
之前自己一直用aspnetpager控件来显示项目中的分页,但是每次都要拖一个aspnetpager的控件进去,感觉很不舒服,因为现在自己写的webform都不用服务器控件了,所以自己仿照aspnetpager写了一个精简实用的返回分页显示的html方法,其他话不说了,直接上代码。
分页显示信息的实体类:
复制代码 代码如下:
public class pager
{
private string _firstpagetext;
/// <summary>
/// 最前一页文字显示 默认显示为"首页"
/// </summary>
public string firstpagetext
{
get {
return string.isnullorempty(_firstpagetext)? "首页" : _firstpagetext;
}
set {
_firstpagetext = value;
}
}
private string _prepagetext;
/// <summary>
/// 上一页文字显示 默认显示为"上一页"
/// </summary>
public string prepagetext
{
get
{
return string.isnullorempty(_prepagetext) ? "上一页" : _prepagetext;
}
set
{
_prepagetext = value;
}
}
private string _nextpagetext;
/// <summary>
/// 下一页文字显示 默认显示为"下一页"
/// </summary>
public string nextpagetext
{
get
{
return string.isnullorempty(_nextpagetext) ? "下一页" : _nextpagetext;
}
set
{
_nextpagetext = value;
}
}
private string _lastpagetext;
/// <summary>
/// 末页文字显示 默认显示为"末页"
/// </summary>
public string lastpagetext
{
get
{
return string.isnullorempty(_lastpagetext) ? "末页" : _lastpagetext;
}
set
{
_lastpagetext = value;
}
}
/// <summary>
/// 总记录数
/// </summary>
public int recordcount { get; set; }
private int _pagesize=15;
/// <summary>
/// 每页分页尺寸 默认为15
/// </summary>
public int pagesize {
get {
return _pagesize == 0 ? 15 : _pagesize;
}set{
_pagesize = value;
}
}
private int _pageindex=1;
/// <summary>
/// 当前页码
/// </summary>
public int pageindex {
get {
return _pageindex == 0 ? 1 : _pageindex;
}
set {
_pageindex = value;
}
}
private int _maxshowpagesize = 10;
/// <summary>
/// 显示页码列表的最大个数 默认为10
/// </summary>
public int maxshowpagesize {
get {
return _maxshowpagesize;
}
set {
_maxshowpagesize = value;
}
}
private string _querystringname;
/// <summary>
/// 页码在浏览器中传值的名称 默认为page
/// </summary>
public string querystringname {
get {
return string.isnullorempty(_querystringname)? "page" : _querystringname;
}
set {
_querystringname = value;
}
}
/// <summary>
/// 页面的url
/// </summary>
public string url {
get {
string url = httpcontext.current.request.url.absoluteuri;//当前页面绝对路径
if (enableurlrewriting)//使用url重写
{
url=url.substring(0, url.lastindexof("/") + 1);//获取当前页面的目录路径
url += urlrewritepattern;
}
else {//普通带问号的页面传值
//demo.aspx
//demo.aspx?a=1
//demo.aspx?page=1
//demo.aspx?a=2&page=1
if (url.contains("aspx?"))
{
if (regex.ismatch(url,@"page=[0-9]*$",regexoptions.ignorecase))//如果存在page=*的字符串
{
url = regex.replace(url, @"page=[0-9]*$", "", regexoptions.ignorecase);//替换掉page=*的字符串
}
url += querystringname + "={0}";
}
else {
url += "?" + querystringname + "={0}";
}
}
return url;
}
}
private bool _enableurlrewriting;
/// <summary>
/// url是否重写 默认为flase
/// </summary>
public bool enableurlrewriting {
get {
return (object)_enableurlrewriting == null ? false : _enableurlrewriting;
}
set {
_enableurlrewriting = value;
}
}
/// <summary>
/// 页面url重写规则,将页码传值用{0}来代替 比如list-1-{0}.html,启用该功能需要将enableurlrewriting属性设为true
/// </summary>
public string urlrewritepattern { get; set; }
private string _classname;
/// <summary>
/// 分页容器的css名称
/// </summary>
public string classname {
get {
return string.isnullorempty(_classname) ? "paginator" : _classname;
}set{
_classname = value;
}
}
private string _currentpagecss;
/// <summary>
/// 当前页面按钮css
/// </summary>
public string currentpagebuttoncss {
get {
return string.isnullorempty(_currentpagecss) ? "cpb" : _currentpagecss;
}set{
_currentpagecss = value;
}
}
private bool _showspantext;
/// <summary>
/// span 标签中文字信息是否显示 默认为false不显示
/// </summary>
public bool showspantext {
get {
return (object)_showspantext == null ? false : _showspantext;
}
set {
_showspantext = value;
}
}
private string _spantextclass;
/// <summary>
/// 分页文字描述span标签css
/// </summary>
public string spantextclass {
get {
return string.isnullorempty(_spantextclass) ? "stc" : _spantextclass;
}
set {
_spantextclass = value;
}
}
private string _submitbuttontext;
/// <summary>
/// 确定按钮文字显示 默认显示"确定"
/// </summary>
public string submitbuttontext {
get {
return string.isnullorempty(_submitbuttontext) ? "确定" : _submitbuttontext;
}
set {
_submitbuttontext = value;
}
}
}
分页显示html代码的拼接方法:
复制代码 代码如下:
public class splitmanager
{
public static string aspnetpagers(pager pager)
{
stringbuilder sb = new stringbuilder();
string attr="";
int pagecount = 0;//当前页面的总层数
int floorcount = 0;//分页的总层数
int currentlastpage = 0;//当前最后一页的页码
int pagenum = pager.recordcount / pager.pagesize + 1;//总页数 1~24
sb.appendformat("<div class=\"{0}\">\n", pager.classname);
attr=pager.pageindex==1?"disabled=disabled":"";//标志当前页第一页是否相等 来控制前俩个按钮的有效性
sb.appendformat(getahtml(attr,string.format(pager.url,1),pager.firstpagetext));//添加最前一页的代码
sb.appendformat(getahtml(attr, string.format(pager.url, pager.pageindex-1), pager.prepagetext));//添加上一页的代码
pagecount = pager.pageindex/pager.maxshowpagesize;//当前页数 0~1~2
pagecount = pager.pageindex % pager.maxshowpagesize == 0 ? pagecount - 1 : pagecount;//清除当 当前页数为分页页码数的整数倍页时除数多一的状况
floorcount = pagenum / pager.maxshowpagesize;//页面层数 0~1~2
currentlastpage=pagenum<pager.maxshowpagesize * (pagecount + 1)?pagenum:pager.maxshowpagesize * (pagecount + 1);
if (pager.pageindex > pager.maxshowpagesize)//当当前序号大于每页页码个数时显示再前端...
{
sb.appendformat(getahtml("", string.format(pager.url, pager.maxshowpagesize * pagecount), "..."));
}
for (int i = pager.maxshowpagesize * pagecount + 1; i <= currentlastpage; i++)
{
if (i == pager.pageindex)//判断循环页面是否为当前页
{
sb.appendformat(getspanhtml(i, pager.currentpagebuttoncss));
}
else {
sb.appendformat(getahtml("", string.format(pager.url, i),i.tostring()));
}
}
if (pager.pageindex <= pager.maxshowpagesize * floorcount)//当当前序号小于倒数第二页页码时显示在后端...
{
sb.appendformat(getahtml("", string.format(pager.url, pager.maxshowpagesize * (pagecount + 1) + 1), "..."));
}
attr = pager.pageindex == pagenum ? "disabled=disabled" : "";//标志当前页最后一页是否相等 来控制后俩个按钮的有效性
sb.appendformat(getahtml(attr, string.format(pager.url, pager.pageindex+1), pager.nextpagetext));//添加后一页的代码
sb.appendformat(getahtml(attr, string.format(pager.url, pagenum), pager.lastpagetext));//添加最后一页的代码
if (pager.showspantext)//是否显示分页文字span标签显示
{
sb.appendformat("<span class=\"" + pager.spantextclass + "\">共{0}页,每页{1}条记录 \n", pagenum, pager.pagesize);
sb.appendformat("到第<input type=\"input\" id=\"jumpnum\" style=\"width:20px;\" name=\"jump\" value=\"{0}\" />页", pager.pageindex == pagenum ? pagenum : pager.pageindex + 1);
sb.appendformat("<a href=\"#\" style=\"float:none;\" onclick=\"javascript:jump();\">" + pager.submitbuttontext + "</a></span>\n");
sb.append(getjumpscript(pager.url));//添加按钮跳转的javascript代码
}
sb.appendformat("</div>");//
return sb.tostring();
}
/// <summary>
/// get the html of a label
/// </summary>
/// <param name="title">a's title</param>
/// <param name="url">the url of a</param>
/// <param name="attr">the attribute</param>
/// <returns>return html string</returns>
private static string getahtml(string attr,string url,string title)
{
return "<a " + attr + " href=\""+url+"\" style=\"margin-right:5px;\">"+title+"</a>\n";
}
/// <summary>
/// get the html of a label
/// </summary>
/// <param name="num">the content of span</param>
/// <param name="classname">class style name</param>
/// <returns>return html string </returns>
private static string getspanhtml(int num, string classname)
{
return "<span class=\"" + classname + "\">" + num + "</span>\n";
}
/// <summary>
/// 获取跳转的javascript代码
/// </summary>
/// <param name="url">当前分页的url规则</param>
/// <returns>返回一个javascript代码</returns>
private static string getjumpscript(string url)
{
string scriptstr = "<script type=\"text/javascript\">\n" +
"function jump(){\n" +
"var jnum=document.getelementbyid(\"jumpnum\").value;\n" +
"if(isnan(jnum)){\n"+
"alert(\"在跳转框中请输入数字!\");\n" +
"}\n"+
"else{\n"+
//"alert(jnum);\n" +
"location.href=string.format(\"" + url + "\",jnum);\n" +
"}\n"+
"}\n"+
"string.format = function() {\n"+
"if( arguments.length == 0 )\n"+
"return null; \n"+
"var str = arguments[0]; \n"+
"for(var i=1;i<arguments.length;i++) {\n"+
"var re = new regexp('\\\\{' + (i-1) + '\\\\}','gm');\n"+
"str = str.replace(re, arguments[i]);\n"+
"}\n"+
"return str;\n"+
"}\n"+
"</script>\n";
return scriptstr;
}
}
最精简必要的几个参数传进去就能显示分页效果了:
复制代码 代码如下:
protected string str = "";
protected void page_load(object sender, eventargs e)
{
pager pager = new pager() { recordcount = 350,
pagesize = 15,
maxshowpagesize=10,
pageindex = convert.toint32(request.querystring["page"]),
showspantext=true};
str = splitmanager.aspnetpagers(pager);
}
仿csdn的分页的效果图
供测试的css:
复制代码 代码如下:
view code
<style type="text/css">
/*分页样式控制的开始*/
.paginator { font: 12px arial, helvetica, sans-serif;
padding:10px 20px 10px 0;
margin: 0px;}
.paginator a {border:solid 1px #ccc;
color:#0063dc;
cursor:pointer;
text-decoration:none;}
.paginator a:visited {padding: 1px 6px;
border: solid 1px #ddd;
background: #f0f1f1;
text-decoration: none;}
.paginator .cpb {border:1px solid #14316b;
font-weight:700;
color:#f0f1f1;
background-color:#1f3d76;}
.paginator a:hover {border:solid 1px #14316b;
color:#14316b;
text-decoration:none;}
.paginator a,.paginator a:visited,.paginator .cpb,.paginator a:hover{float:left;
height:16px;
line-height:16px;
min-width:10px;_width:10px;
margin-right:5px;
text-align:center;
white-space:nowrap;
font-size:12px;
font-family:
arial,simsun;
padding:0 3px;}
.paginator .stc{color:#999;margin-left:20px;}
.paginator .stc a{margin-left:10px;}
/*分页样式控制的结束*/
</style>
同时配合为了配合分页,再给出一个datatable转泛型列表的一个方法和一个分页存储过程。
此转换方法需配合相应的实体类,并且实体类中需对象相应表的字段名,不区分大小写。
复制代码 代码如下:
#region datatable to list/model
/// <summary>
/// datatable to list
/// </summary>
/// <typeparam name="ttype">object type</typeparam>
/// <param name="dt">datatable</param>
/// <returns>return a list model type</returns>
public static list<t> datatabletoobjectlist<t>(datatable dt) where t : new()
{
datarowcollection drc = dt.rows;
int columncount = drc.count;
list<t> result = new list<t>(); //declare the generic type of return
type type = typeof(t);
propertyinfo[] propertys = type.getproperties(bindingflags.ignorecase|bindingflags.instance|bindingflags.public|bindingflags.setproperty); //get the collections of the model
foreach (datarow r in drc)
{
result.add(datarowtoobjectmodel<t>(r, propertys));
}
return result;
}
/// <summary>
/// datarow to a model
/// </summary>
/// <typeparam name="t">the type of model</typeparam>
/// <param name="r">datarow</param>
/// <param name="propertys">the object to model</param>
/// <returns>return a model type</returns>
private static t datarowtoobjectmodel<t>(datarow r, propertyinfo[] propertys) where t : new()
{
t t = new t();
for (int i = 0; i < propertys.length; i++)
{
object obj = r[propertys[i].name];
if (obj != null)
{
if (propertys[i].propertytype == typeof(int))
propertys[i].setvalue(t, publicmethod.getint(obj), null);
if (propertys[i].propertytype == typeof(string))
propertys[i].setvalue(t, obj.tostring(), null);
if (propertys[i].propertytype == typeof(datetime))
propertys[i].setvalue(t, publicmethod.getdatetime(obj), null);
}
}
return t;
}
#endregion
分页存储过程。
复制代码 代码如下:
create procedure [dbo].[proc_splitpage]
-- add the parameters for the stored procedure here
@tblname varchar(255), -- 表名
@strfields varchar(1000) = '*', -- 需要返回的列,默认*
@strorder varchar(255)='', -- 排序的字段名,必填
@strordertype varchar(10)='asc', -- 排序的方式,默认asc
@pagesize int = 10, -- 页尺寸,默认10
@pageindex int = 1, -- 页码,默认1
@strwhere varchar(1500) = '' -- 查询条件 (注意: 不要加 where)
as
declare @strsql varchar(5000)
if @strwhere !=''
set @strwhere=' where '+@strwhere
set @strsql=
'select '+@strfields+' from ('+
'select row_number() over (order by '+@strorder+' '+@strordertype+') as pos,'+@strfields+' '+
'from '+@tblname+' '+@strwhere+
') as sp
where pos between '+str((@pageindex-1)*@pagesize+1)+' and '+str(@pageindex*@pagesize)
exec (@strsql)
以上是全部代码,由于本人还是新手,请大家查找问题并指导,谢谢。
有些朋友需要源码的再此下载,方便测试