传值的方式是通过querystring。
本例子是把整需要的数据查出来再分页的,因为当时做的时候数据很少,只有几十条。
如果数据多的话,可以在存储过程里分页,只是要传页码和记录的条数过来。
控制器:
//分页 ViewBag.PageIndex = pageIndex; ViewBag.PageSize = pageSize; if (agentDetail.ProjectAgentStat!=null) ViewBag.RecondCount = agentDetail.ProjectAgentStat.Count; //如果在存储过程分页就要传这个值 else ViewBag.RecondCount = 0; agentDetail.ProjectAgentStat = agentDetail.ProjectAgentStat.Skip<SProjectAgentStat>((pageIndex - 1) * pageSize).Take(pageSize).ToList<SProjectAgentStat>(); //此处的数据源可以是在存储过程里分好的数据源 ,ProjectAgentStat 为IList的对象
return View(agentDetail);
分页的控件:
namespace System.Web.Mvc { public static class PageHtml { /// <summary> /// 扩展UrlHelper,实现输出分页HTML /// </summary> /// <param name="urlHelper"></param> /// <param name="controllerName">控制器名</param> /// <param name="actionName">行为名</param> /// <param name="pageSize">分页大小</param> /// <param name="pageIndex">当前页码</param> /// <param name="recordCount">总记录数</param> /// <returns></returns> public static MvcHtmlString Pager(this UrlHelper urlHelper, string controllerName, string actionName, int pageSize, int pageIndex, int recordCount) { // 如果分页大小等于0,则返回空字符串 if (pageSize == 0) { return MvcHtmlString.Create(string.Empty); } // 根据总记录数和分页大小计算出分页数量 int pageCount = (int)decimal.Ceiling((decimal)recordCount / (decimal)pageSize); // 首页、末页 string firstStr = string.Empty; string lastStr = string.Empty; if (recordCount > 0) { string firstUrl = urlHelper.Action(actionName, controllerName, new { pagenum = 1 }); firstStr = "<a href=‘" + firstUrl + "‘>首页</a>"; string lastUrl = urlHelper.Action(actionName, controllerName, new { pagenum = pageCount }); lastStr = "<a href=‘" + lastUrl + "‘>末页</a>"; } else { firstStr = "首页"; lastStr = "末页"; } // 上一页 string preStr = string.Empty; if (pageIndex > 1 && pageIndex <= pageCount) { string prevUrl = urlHelper.Action(actionName, controllerName, new { pagenum = pageIndex - 1 }); preStr = "<a href=‘" + prevUrl + "‘>上一页</a>"; } else { preStr = "上一页"; } // 下一页 string nextStr = string.Empty; if (pageIndex > 0 && pageIndex < pageCount) { string nextUrl = urlHelper.Action(actionName, controllerName, new { pagenum = pageIndex + 1 }); nextStr = "<a href=‘" + nextUrl + "‘>下一页</a>"; } else { nextStr = "下一页"; } // 页码 string numStr = string.Empty; if (pageCount > 0) { // 遍历输出全部的页码 for (int i = 1; i <= pageCount; i++) { string numUrl = urlHelper.Action(actionName, controllerName, new { pagenum = i }); // 当前页码加粗 if (i == pageIndex) { numStr += "[<a href=‘" + numUrl + "‘><strong>" + i + "</strong></a>] "; } else { numStr += "[<a href=‘" + numUrl + "‘>" + i + "</a>] "; } } } string pageStr = firstStr + " " + preStr + " " + numStr + nextStr + " " + lastStr; return MvcHtmlString.Create(pageStr); } } }
视图:
@Url.Pager("project", "agentdetail/" + @Model.ProjectLineStat.ProjectId, (int)ViewBag.PageSize, (int)ViewBag.PageIndex, (int)ViewBag.RecondCount)
URL的样子为:/project/agentdetail/61?pagenum=2
参考网址:http://blog.bossma.cn/asp_net_mvc/asp-net-mvc-url-pager/