分页
OK~~第一次来博客园扯扯淡。
分页其实很简单,就是在action中对数据进行切割,然后用page判断拿第几块的数据,然后将数据扔到view中显示。很简单~~有木有。
下面是代码:
1 public ActionResult Index(int? page) 2 { 3 //获取搜索信息 4 int userId = (string.IsNullOrEmpty(Request.Params["userid"]) ? 0 : Convert.ToInt32(Request.Params["userid"])); 5 string productname = string.IsNullOrEmpty(Request.Params["productname"]) ? "" : Request.Params["productname"].Trim(); 6 string status = string.IsNullOrEmpty(Request.Params["status"]) ? "" : Request.Params["status"].Trim(); 7 8 var orders = from x in context.PurchaseOrders 9 where x.Product.Name.Contains(productname == "" ? x.Product.Name : productname) && 10 x.Status == (status == "" ? x.Status : status)&& 11 x.IsDelete == false && 12 x.CreateBy == (userId == 0 ? x.CreateBy : userId) 13 select x; 14 ViewBag.User = context.Users.ToList(); 15 return View(orders.OrderByDescending(x => x.CreateAt).ToPagedList(page ?? 1, 30)); 16 }
其中int? page是指这个page可为null的int类型。如果url是www.xxx.com/home/index?page=12,就是说第12页。后面的page??1,30是指page为空时传入1,不为空时传入page的值,后面的30是ToPagedList的第二个参数,下面会给出ToPagedList的代码。还有就是说这个数据在分页前要排序一下,不然会出错地喽。
下面是ToPagedList的代码:
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Collections.Generic; using System.Text; using System.Web.Mvc; using System.Text.RegularExpressions; namespace Purchase.Helpers { public class PagedList<T> : List<T> { public int CurrentPageIndex { get; set; } public int PageSize { get; set; } public int TotalItemCount { get; set; } public int TotalPageCount{get; private set;} public int StartRecordIndex{get; private set;} public int EndRecordIndex{get; private set;} public PagedList(IList<T> items,int pageIndex,int pageSize) { PageSize = pageSize; TotalItemCount = items.Count; TotalPageCount = (int)Math.Ceiling(TotalItemCount / (double)PageSize); CurrentPageIndex = pageIndex; StartRecordIndex=(CurrentPageIndex - 1) * PageSize + 1; EndRecordIndex = TotalItemCount > pageIndex * pageSize ? pageIndex * pageSize : TotalItemCount; for (int i = StartRecordIndex-1; i < EndRecordIndex;i++ ) { Add(items[i]); } } public PagedList(IEnumerable<T> items, int pageIndex, int pageSize, int totalItemCount) { AddRange(items); TotalItemCount = totalItemCount; TotalPageCount = (int)Math.Ceiling(totalItemCount / (double)pageSize); CurrentPageIndex = pageIndex; PageSize = pageSize; StartRecordIndex = (pageIndex - 1) * pageSize + 1; EndRecordIndex = TotalItemCount > pageIndex * pageSize ? pageIndex * pageSize : totalItemCount; } } public static class PageLinqExtensions { public static PagedList<T> ToPagedList<T>(this IQueryable<T> allItems,int pageIndex,int pageSize) { if (pageIndex < 1) pageIndex = 1; var itemIndex = (pageIndex - 1) * pageSize; var pageOfItems = allItems.Skip(itemIndex).Take(pageSize); var totalItemCount = allItems.Count(); return new PagedList<T>(pageOfItems, pageIndex, pageSize, totalItemCount); } } public static class PagerHelper { public static string Pager(this HtmlHelper helper, int pageSize, int currentPageIndex, int totalPages, int totalItemCount) { bool hasPreviousPage = (currentPageIndex > 1); bool hasNextPage = (currentPageIndex < totalPages); StringBuilder sb = new StringBuilder(); string reqUrl = helper.ViewContext.HttpContext.Request.RawUrl; string link = ""; Regex re = new Regex(@"page=(\d+)|page=", RegexOptions.IgnoreCase); MatchCollection results = re.Matches(reqUrl); if (results.Count > 0) { link = reqUrl.Replace(results[0].ToString(), "page={0}"); } else if (reqUrl.IndexOf("?") < 0) { link = reqUrl + "?page={0}"; } else { link = reqUrl + "&page={0}"; } if (totalItemCount > pageSize) { sb.Append("<div class=\"pager\">"); if (hasPreviousPage) { sb.Append("<a href=\"" + string.Format(link,(currentPageIndex -1).ToString()) + "\"><img src='/images/left_arrow.gif' alt='上一页' title='上一页' /> 上一页</a>"); } int beginPage = currentPageIndex - 2,endPage = currentPageIndex + 2; beginPage = beginPage<1?1:beginPage; endPage = endPage > totalPages?totalPages:endPage; if (beginPage >= 2) { sb.Append("<a href=\"?"+ string.Format(link,"1") +"\">1</a>"); if(beginPage >2) sb.Append("..."); } for (int i = beginPage; i <= endPage; i++) { if (i == currentPageIndex) sb.Append("<span>").Append(i.ToString()).Append("</span>"); else sb.Append("<a href=\"" + string.Format(link,i) + "\">" + i + "</a>"); } if (endPage <= totalPages -1) { if(endPage < totalPages -1) sb.Append("..."); sb.Append("<a href=\"" + string.Format(link, totalPages) + "\">" + totalPages + "</a>"); } if (hasNextPage) { sb.Append("<a href=\"" + string.Format(link, (currentPageIndex + 1).ToString()) + "\">下一页 <img src='/images/right_arrow.gif' alt='下一页' title='下一页' /></a>"); } sb.Append("</div>"); } return sb.ToString(); } public static string Pager<T>(this HtmlHelper helper, PagedList<T> pagedList) { if (pagedList == null) return ""; return Pager(helper, pagedList.PageSize, pagedList.CurrentPageIndex, pagedList.TotalPageCount, pagedList.TotalItemCount); } } }
记得把这个namespace换成自已的,不要用我的空间名。还有在controllers中引入这个空间。不要说你不会引用,using~~,you know~~。引入这个空间入就可以用ToPagedList了呦。
还有个问题是在view中怎么获取这个模型呢。
@model PagedList<PurchaseOrder>
@using Purchase.Models
@using Purchase.Helpers
直接在view的头部写入这个 当然这个helpers类要写喽 如果你之前的空间名改了的话就写你的空间名喽。模型就是PagedList类型,别给写错了。
下面是显示第几页的html
<h3 style="float:right;margin:20px;">@Html.Raw(Html.Pager(Model))</h3>
OK了。这个h3标签你可以自已改。