zodream梦想开源/个人编程日记

zodream梦想开源/个人编程日记

简单的个人编程日记

马上订阅 zodream梦想开源/个人编程日记 RSS 更新: https://zodream.cn/blog/rss

Net Core 实现一个简单的分页功能

2021年4月4日 06:29
编程技术

主要代码

    [HtmlTargetElement("pagination")]
    public class PagerTagHelper : TagHelper
    {
        // 总共有多少条记录
        public long Total { get; set; } = 0;

        // 一页有多少条记录
        public int PerPage { get; set; } = 20;

        // 当前第几页
        public int Page { get; set; } = 1;

        // 分页链接的最多显示个数
        public int PageLength { get; set; } = 7;

        private string url;
        // 当前网址
        public string Url
        {
            get { return url; }
            set {
                if (value.IndexOf('?') < 0)
                {
                    url = value + "?page=";
                    return;
                }
                url = Regex.Replace(value, @"([\?\&])page=\d+\&*", "$1") + "&page=";
            }
        }

        // 是否显示上一页下一页
        public bool DirectionLinks { get; set; } = false;

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = "div";
            var html = new StringBuilder();
            var items = initLinks(out bool canPrevious, out bool canNext);
            html.Append("<ul class=\"pagination\">");
            if (DirectionLinks && canPrevious)
            {
                html.AppendFormat("<li class=\"page-item{0}\"><a class=\"page-link\" href=\"{1}{2}\" aria-label=\"Previous\"><span aria-hidden=\"true\">«</span><span class=\"sr-only\">上一页</span></a></li>", 
                    canPrevious ? ""...

剩余内容已隐藏

查看完整文章以阅读更多