ASP.NET分页

昨天帮同学写的分页Demo,由于同学不会MVC 我就用webform写了。

其实分页很简单,只要把握PageSize RecordCount PageIndex PageCount即可 

PageCount为(int)Math.Ceiling((decimal)RecordCount / PageSize)


1、ajax模式

代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="paginationDemo.aspx.cs" Inherits="myArticle.paginationDemo" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <link rel="stylesheet" href="Css/article.css" />
    <style type="text/css">
        .page_nav {
            padding-top: 20px;
        }

        .pagination {
            text-align: center;
        }

            .pagination a:first-child, .pagination span:first-child {
                border-left-width: 1px;
                -moz-border-radius-bottomleft: 4px;
                -moz-border-radius-topleft: 4px;
                -webkit-border-bottom-left-radius: 6px;
                border-bottom-left-radius: 6px;
                -webkit-border-top-left-radius: 6px;
                border-top-left-radius: 6px;
            }

            .pagination a:last-child , .pagination span:last-child{
                -webkit-border-top-right-radius: 6px;
                border-top-right-radius: 6px;
                -webkit-border-bottom-right-radius: 6px;
                border-bottom-right-radius: 6px;
            }

            .pagination a, .pagination span {
                padding: 6px 12px;
                line-height: 20px;
                text-decoration: none;
                background-color: #ffffff;
                border: 1px solid #dddddd;
                border-left-width: 0;
            }

            .pagination span {
                color: #999;
            }

                .pagination span.active {
                    color: #f00;
                }
    </style>
    <script type="text/javascript" src="Scripts/jquery-1.7.1.min.js"></script>
    <script type="text/javascript" src="Scripts/jquery.pagination.js"></script>
    <script type="text/javascript">
        $(function () {
            var recordcount = "<%=RecordCount%>";
            $('.pagination').pagination({
                recordcount: recordcount,
                pagesize: 10,
                distance: 3,
                callback: function (pageindex, pagesize) {
                    $.ajax({
                        type: "post",
                        url: "/WebServices/WebService.asmx/GetArticlePage",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        data: "{ 'PageIndex':" + (pageindex - 1) + ", 'PageSize':" + pagesize + ", 'Sorting': 'Id ASC' }",
                        beforeSend: function () {
                            $("#articleloding").show();
                        },
                        success: function (result) {
                            $("#articleloding").hide();
                            var article = result.d;
                            var html = "";
                            $.each(article, function (key, value) {
                                html += '<li class="result"><a href="releaseArticle.html?ftitle=' + value.FTitle + '" target="_blank" class="article_thumbnail">';
                                html += '<img  src="images\/' + value.FImgUrl + '" alt="" width="100" height="100"/></a>';
                                html += '<div class="block"><h2><a href="releaseArticle.html?ftitle=' + value.FTitle + '"  target="_blank">' + value.FTitle + '</a>';
                                html += '<span class="state">' + value.FState + '</span></h2><div class="memo">';
                                html += '<p>' + value.FMemo + '</p> </div><span class="tags">';
                                html += '<strong>Tags:</strong>';
                                html += '<a href="releaseArticle.html?ftitle=' + value.FTitle + '" target="_blank">' + value.FTags + '</a></span></div></li>';
                            });
                            $(".article_ul").html(html);
                            var offset = $('div.article_list').offset();
                            window.scrollTo(offset.x, offset.y);
                        }
                    });
                }
            });
        });
    </script>
</head>
<body>
    <div class="article">
        <div class="article_nav">当前分类:IT之外</div>
        <div class="article_list">
            <ul class="article_ul">
                <p id="articleloding" style="display: none">努力加载中......</p>
            </ul>
            <div class="page_nav">
                <div id="pagination" class="pagination">
                </div>
            </div>
        </div>
    </div>
    <p>test</p>
</body>
</html>
下面的分页jquery插件是本人所写,欢迎指点。 loadfirst 参数为flase表明第一页数据由服务器产生,其他页数据通过ajax加载。默认为true,都通过ajax加载
(function ($) {
    var pagesize, recordcount, pageindex, distance, callback, loadfirst, pagecount, element;

    var getOptions = function (element) {
        var options = element.data('options');
        if (options) {
            return options;
        }
        else {
            $.error('The element must be initialized first');
        }
    }

    var producelink = function (i, txt) {
        return '<a href="javascript:void(0);" onclick="return $.page(' + i + ');">' + txt + '</a>';
    }

    var page = $.page = function (pageindex) {
        if (loadfirst) {
            callback(pageindex, pagesize);
        } else {
            loadfirst = true;
        }
        var linklist = [];
        if (pageindex == 1) {
            linklist.push("<span>前一页</span>");
        }
        else {
            linklist.push(producelink(pageindex - 1, '前一页'));
        }
        for (var i = 1; i <= pagecount; i++) {
            if (i == pageindex - distance) {
                if (i == 1) {
                    linklist.push(producelink(1, 1));
                } else {
                    linklist.push(producelink(1, 1) + '<span>...</span>');
                }
                continue;
            }
            if (i == pageindex + distance) {
                if (i == pagecount) {
                    linklist.push(producelink(pagecount, pagecount));
                } else {
                    linklist.push('<span>...</span>' + producelink(pagecount, pagecount));
                }
                continue;
            }
            if (i > pageindex - distance && i < pageindex + distance && i != pageindex) {
                linklist.push(producelink(i, i));
                continue;
            }
            if (i == pageindex) {
                linklist.push('<span class="active">' + i + '</span>');
            }
        }
        if (pageindex == pagecount) {
            linklist.push('<span>后一页</span>');
        } else {
            linklist.push(producelink(pageindex + 1, '后一页'));
        }
        element.html(linklist.join(''));
        return false;
    }

    var methods = {
        init: function (options) {
            return this.each(function () {
                var $this = $(this);
                options = $.extend({}, $.fn.pagination.defaults, options);
                $this.data('options', options);
                methods['load'].call($this);
            })
        },
        load: function () {
            element = $(this);
            var options = getOptions(element);

            pagesize = options.pagesize;
            recordcount = options.recordcount;
            pageindex = options.pageindex;
            distance = options.distance;
            callback = options.callback;
            loadfirst = options.loadfirst;
            if (pagesize && recordcount && pageindex && distance) {
                pagecount = Math.ceil(recordcount / pagesize);
                page(pageindex);
            } else {
                $.error('args error------jquery.pagination.js');
            }
        }
    }

    $.fn.pagination = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        }
        else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        }
        else {
            $.error('Method ' + method + ' does not exist on jQuery.tags');
        }
    };

    $.fn.pagination.defaults = {
        loadfirst: true,
        pagesize: 10,
        recordcount: null,
        pageindex: 1,
        distance: 3,
        callback: function (pageindex, pagesize) { return false; }
    };
})(jQuery);

 String connstr = "Data Source=.;Initial Catalog=Article;Integrated Security=True";

        [WebMethod]
        public List<Article> GetArticlePage(int PageIndex, int PageSize, string Sorting)
        {
            if (!Regex.IsMatch(PageIndex.ToString(), @"^\d+$") || !Regex.IsMatch(PageSize.ToString(), @"^\d+$")) { return null; }
            List<Article> articlelist = new List<Article>();
            SqlConnection con = new SqlConnection(connstr);
            con.Open();
            string sql = "select * from (select row_number() over (order by @Sorting) as row,* from tArticle) as tArticle where row between @PageSize*@PageIndex and @PageSize*(@PageIndex+1)";
            SqlCommand cmd = new SqlCommand(sql, con);
            cmd.Parameters.Add(new SqlParameter("@PageIndex", PageIndex));
            cmd.Parameters.Add(new SqlParameter("@PageSize", PageSize));
            cmd.Parameters.Add(new SqlParameter("@Sorting", Sorting));
            SqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                Article article = new Article();
                article.Id = reader["Id"].ToString();
                article.FTitle = reader["fTitle"].ToString();
                article.FTags = reader["fTags"].ToString();
                article.FState = reader["fState"].ToString();
                article.FInfo = reader["fInfo"].ToString();
                article.FImgUrl = reader["fImgUrl"].ToString();
                article.FMemo = reader["fMemo"].ToString();
                articlelist.Add(article);

            }
            reader.Close();
            con.Close();
            return articlelist;
        }

2、纯后台模式

代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="article.aspx.cs" Inherits="myArticle.article" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
        <link rel="stylesheet" href="Css/article.css" />
     <style type="text/css">
         .article {
            position:absolute;
         }
         .pagnation {
            position:relative;
            top:30px;
            right:0px;
            float:right;
         }
         .pagnation a,.pagnation span {
           margin-left:10px;
         }
             .pagnation span {
               color: #999;
             }
         .pagnation span.active {
             color:#f00;
         }
     </style>
</head>
<body>
<div class="article">
   <div class="article_nav">当前分类:IT之外</div>
   <div class="article_list">
        <ul class="article_ul">
          <%foreach (myArticle.WebServices.Article value in articlelist) {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append(string.Format("<li><a href=\"releaseArticle.html?ftitle={0}\" target=\"_blank\" class=\"article_thumbnail\">", value.FTitle));
                stringBuilder.Append(string.Format("<img  src=\"images/{0}\" alt=\"\" width=\"100\" height=\"100\"/></a>", value.FImgUrl));
                stringBuilder.Append(string.Format("<div class=\"block\"><h2><a href=\"releaseArticle.html?ftitle={0}\"  target=\"_blank\">{1}</a>", value.FTitle, value.FTitle));
                stringBuilder.Append(string.Format("<span class=\"state\">{0}</span></h2><div class=\"memo\">", value.FState));
                stringBuilder.Append(string.Format("<p>{0}</p> </div><span class=\"tags\">", value.FMemo));
                stringBuilder.Append("<strong>Tags:</strong>");
                stringBuilder.Append(string.Format("<a href=\"releaseArticle.html?ftitle={0}\" target=\"_blank\">{1}</a></span></div></li>", value.FTitle, value.FTags));
                Response.Write(stringBuilder.ToString());
            } %>
       </ul>
    </div>
    <div class="pagnation">
        <% 
            int distance = 3;  
            if (pageinfo.PageIndex == 1) { Response.Write("<span>前一页</span>"); }
            else
            {
                Response.Write("<a href=\"Article.aspx?PageIndex=" + (pageinfo.PageIndex - 1) + "\">前一页</a>");
            }
            for (int i = 1; i <= pageinfo.PageCount; i++)
            {
                if (i == pageinfo.PageIndex - distance)
                {
                    if (i == 1)
                    {
                        Response.Write("<a href=\"Article.aspx?PageIndex=1\">1</a>");
                    }
                    else
                    {
                        Response.Write("<a href=\"Article.aspx?PageIndex=1\">1</a><span>...</span>");
                    }
                }
                if (i == pageinfo.PageIndex + distance)
                {
                    if (i == pageinfo.PageCount)
                    {
                        Response.Write("<a href=\"Article.aspx?PageIndex=" + pageinfo.PageCount + "\">" + pageinfo.PageCount + "</a>");
                    }
                    else
                    {
                        Response.Write("<span>...</span><a href=\"Article.aspx?PageIndex=" + pageinfo.PageCount + "\">" + pageinfo.PageCount + "</a>");
                    }
                }
                if (i > pageinfo.PageIndex - distance && i < pageinfo.PageIndex + distance && i != pageinfo.PageIndex)
                {
                    Response.Write("<a href=\"Article.aspx?PageIndex=" + i + "\">" + i + "</a>");
                }
                if (i == pageinfo.PageIndex)
                {
                    Response.Write("<span class=\"active\">" + i + "</span>");
                }
            }
            if (pageinfo.PageIndex == pageinfo.PageCount)
            {
                Response.Write("<span>后一页</span>");
            }
            else
            {
                Response.Write("<a href=\"Article.aspx?PageIndex=" + (pageinfo.PageIndex + 1) + "\">后一页</a>");
            }
        %>
    </div>   
</div>
</body>
</html>


    public partial class article : System.Web.UI.Page
    {
        public List<Article> articlelist = new List<Article>();

        public PagingInfo pageinfo = new PagingInfo();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["PageIndex"] == null){
                pageinfo.PageIndex = 1;
            }
            else {
                var PageIndex = Request.QueryString["PageIndex"].ToString();
                if (Regex.IsMatch(PageIndex, @"^[1-9]\d*$")){
                    pageinfo.PageIndex = Int32.Parse(Request.QueryString["PageIndex"].ToString());
                }
                else {
                    Response.End();
                }
            }

            String connstr = "Data Source=.;Initial Catalog=Article;Integrated Security=True";
            SqlConnection con = new SqlConnection(connstr);
            String sql = "select count(*) from tArticle";
            con.Open();
            SqlCommand cmd = new SqlCommand(sql, con);
            pageinfo.RecordCount = (int)cmd.ExecuteScalar();

            if (pageinfo.PageIndex > pageinfo.PageCount) {
                pageinfo.PageIndex = pageinfo.PageCount;
            }

            sql = "select * from (select row_number() over (order by Id) as row,* from tArticle) as tArticle where row between @PageSize*(@PageIndex-1) and @PageSize*@PageIndex";
            cmd = new SqlCommand(sql, con);
            cmd.Parameters.Add(new SqlParameter("@PageIndex",pageinfo.PageIndex));
            cmd.Parameters.Add(new SqlParameter("@PageSize",pageinfo.PageSize));
            SqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                Article article = new Article();
                article.Id = reader["Id"].ToString();
                article.FTitle = reader["fTitle"].ToString();
                article.FTags = reader["fTags"].ToString();
                article.FState = reader["fState"].ToString();
                article.FInfo = reader["fInfo"].ToString();
                article.FImgUrl = reader["fImgUrl"].ToString();
                article.FMemo = reader["fMemo"].ToString();
                articlelist.Add(article);

            }
            reader.Close();
            con.Close();
        }
    }

    public class PagingInfo
    {
        public int PageSize
        {
            get { return 10; }
        }
        public int RecordCount { get; set; }
        public int PageIndex { get; set; }
        public int PageCount
        {
            get { return (int)Math.Ceiling((decimal)RecordCount / PageSize); }
        }
    }

对于pagelink 在asp.net mvc中是写成局部视图的,webform里面我还不会。

猜你喜欢

转载自blog.csdn.net/zhuankeshumo/article/details/17137107