分页系列之二:ASP.NET MVC 网页分页

PageHelper.cs

using System;
using System.Web;

namespace MvcApp.CommonClass
{
    public class PageHelper
    {
        /// <summary>
        /// 创建HTML分页代码
        /// </summary>
        /// <param name="page">当前页号</param>
        /// <param name="pageSize">每页记录数</param>
        /// <param name="total">总记录数</param>
        /// <returns>返回HTML分页代码</returns>
        public static string SetPageHtml(int page, int pageSize, int total)
        {
            if (total == 0)
            {
                return "";
            }
            int totalPage, beginPage, endPage;
            string beginHtml, endHtml, middleHtml = "";
            string param = HttpContext.Current.Request.QueryString["Page"];
            string query = HttpContext.Current.Request.Url.Query;
            //去掉URL中现有的page参数
            if (param != null)
            {
                query = query.Replace($"&page={param}", "").Replace($"page={param}&", "").Replace($"?page={param}", "");
            }
            query = query == "" ? "?page=" : query + "&page=";
            totalPage = (int)Math.Ceiling((double)total / pageSize);
            //生成首尾页、上下页HTML
            if (totalPage == 1)
            {
                beginHtml = "<span>首页</span><span>上一页</span>";
                endHtml = "<span>下一页</span><span>尾页</span>";
            }
            else if (page == 1)
            {
                beginHtml = "<span>首页</span><span>上一页</span>";
                endHtml = $"<a href=\"{query}{page + 1}\">下一页</a><a href=\"{query}{totalPage}\">尾页</a>";
            }
            else if (page == totalPage)
            {
                beginHtml = $"<a href=\"{query}1\">首页</a><a href=\"{query}{page - 1}\">上一页</a>";
                endHtml = "<span>下一页</span><span>尾页</span>";
            }
            else
            {
                beginHtml = $"<a href=\"{query}1\">首页</a><a href=\"{query}{page - 1}\">上一页</a>";
                endHtml = $"<a href=\"{query}{page + 1}\">下一页</a><a href=\"{query}{totalPage}\">尾页</a>";
            }
            //计算起止页
            if (totalPage <= 7)
            {
                beginPage = 1;
                endPage = totalPage;
            }
            else if (page <= 4)
            {
                beginPage = 1;
                endPage = 7;
            }
            else if (totalPage - page <= 3)
            {
                endPage = totalPage;
                beginPage = endPage - 6;
            }
            else
            {
                beginPage = page - 3;
                endPage = beginPage + 6;
            }
            //生成中间页HTML
            for (int i = beginPage; i <= endPage; i++)
            {
                if (i == page)
                {
                    middleHtml += $"<em>{i}</em>";
                }
                else
                {
                    middleHtml += $"<a href=\"{query}{i}\">{i}</a>";
                }
            }
            return beginHtml + middleHtml + endHtml + " 总共" + total + "条、" + totalPage + "";
        }
        /// <summary>
        /// 获取当前页号
        /// </summary>
        /// <returns></returns>
        public static int GetCurrentPage()
        {
            if (int.TryParse(HttpContext.Current.Request.QueryString["Page"], out int page))
            {
                return page;
            }
            return 1;
        }
    }
}

模型

using System;

namespace MvcApp.Models
{
    public class Article
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public DateTime UpdateTime { get; set; }
    }
}

控制器

using MvcApp.CommonClass;
using MvcApp.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Web.Mvc;

namespace MvcApp.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult List()
        {
            int page = PageHelper.GetCurrentPage(); //当前页码
            List<Article> listArticle = new List<Article>();
            SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);
            SqlCommand cmd = new SqlCommand("procArticleList", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Page", page);
            cmd.Parameters.AddWithValue("@PageSize", 30);   //每页记录数,也可以由前端传递过来,由用户选择
            cmd.Parameters.AddWithValue("@NodeID", Request.QueryString["nodeID"]);
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                listArticle.Add(new Article
                {
                    ID = (int)dr["ID"],
                    Title = dr["Title"].ToString(),
                    UpdateTime = (DateTime)dr["UpdateTime"]
                });
            }
            dr.NextResult();    //记录总数
            dr.Read();
            int total = Convert.ToInt32(dr[0]);  //记录总数
            dr.Close();
            conn.Close();
            ViewBag.PageHtml = PageHelper.SetPageHtml(page, 30, total);
            return View(listArticle);
        }
    }
}

视图

@model IEnumerable<MvcApp.Models.Article>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>分页示例</title>
<link href="/images/css.css?v=2020-5-13" rel="stylesheet">
</head>
<body>
<ul>
@foreach (var item in Model)
{
    <li><a href="/Home/Detail/@item.ID" target="_blank">@item.Title</a>@item.UpdateTime.ToString("yyyy.MM.dd")</li>
}
</ul>
<p class="page">@Html.Raw(ViewBag.PageHtml)</p>
</body>
</html>

 相关CSS

/*分页*/
p.page {padding:0px;margin:16px auto;color:#333;text-align:center;font:12px Verdana,Arial,Helvetica,sans-serif;}
p.page a,p.page span,p.page em {padding:4px 6px;margin-right:3px;}
p.page a {border:#ABCEE9 1px solid;color:#ABCEE9;text-decoration:none;}
p.page a:hover {background:#D3F4FC;}
p.page span {border:#ccc 1px solid;color:#ccc;}
p.page em {border:#2670C9 1px solid;font-weight:bold;color:#2670C9;font-style:normal;}

效果如下:

----分页系列----

一、SQL Server 分页存储过程

二、ASP.NET MVC 网页分页

三、网页滚动加载分页数据

四、微信小程序滚动加载分页数据

五、WinForm + DevExpress 自制分页控件

posted on 2021-04-26 20:12  羊茂林  阅读(150)  评论(2编辑  收藏  举报

导航