浅谈MVC3自定义分页

分页这个东西刚开始自己来写的时候感觉很复杂,在网络上分页大部分都是比较成熟分页空间,对于新手的我查看其代码有时真的看的不太明白,最近自己在用到MVC3做分页查看数据,有些总结

1、分页基本参数:pageSize、pageIndex、Total

其中Total,这个也就是要查询数据的总个数,到时用来生成分页控件

2、Controll 部分

public ActionResult Paging(int? pageIndex, int pageSize = 5)
        {
            int total = 0;
            pageIndex = pageIndex == null ? 0 : pageIndex;

            //获取数据
            MercuryDbExEntities db = new MercuryDbExEntities();
            total = db.Users.Count();
            var result = db.Users.OrderBy(p => p.Id).Skip(pageIndex.Value * pageSize).Take(pageSize);

            ViewBag.Pagination = new Pagination(pageIndex, pageSize, total);
            return View(result);
        }

3、

public class Pagination
    {
        public int? PageIndex { get; private set; }//当前页号减一的值
        public int PageSize { get; private set; } //每页显示的内容数量
        public int TotalPages { get; private set; }//总页数
        public int Start { get; private set; }//当前页面,显示的第一个页号(比如在中间的页面,页号显示是9号到16号,9就是Start)
        public int End { get; private set; }//当前页面,显示的最后一个页号

        public Pagination(int? pageIndex, int pageSize, int totalcount)
        {
            PageIndex = (pageIndex ?? 0);
            PageSize = pageSize; ;
            TotalPages = (int)Math.Ceiling(totalcount / (double)PageSize);

            int size;//判定每个页面显示多少个页号
            if (TotalPages > 6)//这里规定每个页面显示6个页号
            {
                size = 6;
                //定义每个页面的页号从几开始
                if (pageIndex > 2 && pageIndex < TotalPages - (size - 2))
                {
                    Start = (pageIndex ?? 0) - 1;
                }
                else if (pageIndex >= TotalPages - (size - 2))
                {
                    Start = TotalPages - size + 1;
                }
                else
                {
                    Start = 1;
                }
            }
            else
            {
                size = TotalPages;
                Start = 1;

            }

            End = Start + size - 1;
        }

        // 为“上一页”“下一页”导航备用
        public bool HasPreviousPage
        {
            get { return (PageIndex > 0); }
        }

        public bool HasNextPage
        {
            get { return (PageIndex + 1 < TotalPages); }
        }
    }

4、View部分

--内容展示部分

@model IEnumerable<Mvc3_Test.DataBase.Users>
@using Mvc3_Test.Htmlhelpers
@{
    ViewBag.Title = "Paging";
}
<h2>内容展示</h2>
@foreach (var item in Model)
{
    <p>
        @item.Id <b>|</b>@item.LoginName
    </p>
}
<hr />
@Html.Partial("_Pagination", (Mvc3_Test.Htmlhelpers.Pagination)ViewBag.Pagination)

--分页标签展示部分

@model Mvc3_Test.Htmlhelpers.Pagination
@using Mvc3_Test.Htmlhelpers
<div class="clearfix pagination">
    <div class="pagination-inner">
        @if (Model.Start > 1)
        {
            //如果当前页面超过第二页则显示第一页“1...”的链接
            string url = Html.UrlSet(Request, "pageIndex", 0); 
            <a title="第一页1..." href="@url">1...</a>                  
        }
        @for (int i = Model.Start; i <= Model.End; i++)
        {
            string url = Html.UrlSet(Request, "pageIndex", i - 1);
            if (i == Model.PageIndex + 1)
            {
                //在当前页面的几个页号中寻找当前页号               
                <a title="当前第 @i.ToString() 页"  class="current" href="@url">@i.ToString()</a>           
            }
            else
            {
                <a title="前往第 @i.ToString() 页@i.ToString()"  href="@url">@i.ToString()</a>           
            }
        }
        @if (Model.End < Model.TotalPages && Model.PageIndex - Model.Start < 2)
        {
            //最后一页
            string totalPages = (@Model.TotalPages).ToString();
            string url = Html.UrlSet(Request, "pageIndex", Model.TotalPages - 1);            
            <a title="最后一页@totalPages"  href="@url">@totalPages</a>
        }
    </div>
</div>

【说明:其中大家看到,在对于A标签的href中代码进行了@url处理,因为有时项目中用来展示数据的地方会有很多,所以为了使得“分页标签展示页面”得以重用性,又增加了一个类:HtmlHelpers】

5、HtmlHelpers类

public static class HtmlHelpers
    {
        public static string UrlSet(this HtmlHelper helper, HttpRequestBase request, string queryName, object queryValue)
        {
            if (queryName != null && queryValue != null)
            {
                string path = request.Path;
                NameValueCollection query = new NameValueCollection(request.QueryString);
                query.Set(queryName, queryValue.ToString());
                return CreateUrl(path, query);
            }
            return request.RawUrl;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="request"></param>
        /// <param name="queryName"></param>
        /// <param name="queryValue"></param>
        /// <returns></returns>
        public static string UrlAdd(this HtmlHelper helper, HttpRequestBase request, string queryName, object queryValue)
        {
            if (queryName != null && queryValue != null)
            {
                string path = request.Path;
                NameValueCollection query = new NameValueCollection(request.QueryString);
                query.Add(queryName, queryValue.ToString());
                return CreateUrl(path, query);
            }
            return request.RawUrl;
        }

        public static string UrlRemove(this HtmlHelper helper, HttpRequestBase request, string queryName)
        {
            if (queryName != null)
            {
                string path = request.Path;
                NameValueCollection query = new NameValueCollection(request.QueryString);
                query.Remove(queryName);
                return CreateUrl(path, query);
            }
            return request.RawUrl;
        }

        public static string UrlRemove(this HtmlHelper helper, HttpRequestBase request, string queryName, object queryValue)
        {
            if (queryName != null && queryValue != null)
            {
                string path = request.Path;
                NameValueCollection query = new NameValueCollection(request.QueryString);

                string[] values = query.GetValues(queryName);
                List<string> vs = values.ToList();
                vs.Remove(queryValue.ToString());
                query.Remove(queryName);
                foreach (var item in vs)
                {
                    query.Add(queryName, item);
                }

                return CreateUrl(path, query);
            }
            return request.RawUrl;
        }

        private static string CreateUrl(string path, NameValueCollection query)
        {
            string url = path;
            if (query != null && query.Count != 0)
            {
                url += "?";
                for (int i = 0; i < query.Count; i++)
                {
                    string key = query.GetKey(i);
                    string[] values = query.GetValues(key);
                    for (int j = 0; j < values.Length; j++)
                    {
                        url += key + "=" + values[j] + "&";
                    }
                }

                url = url.TrimEnd('&');
            }
            return url;
        }
    }

posted on 2011-07-11 19:26  水星曙光  阅读(3320)  评论(2编辑  收藏  举报