这里的分页代码和Contrib中略有不同,一会儿我们来讲解这个不同的原因。
添加一个Controller:
Controller
1 public ActionResult CustomPager(int? page) 2 { 3 int pageSize = 3; 4 int pageNumber = page ?? 1; 5 var list = ListNews.GetList() 6 .Where(p => p.Title.Contains(Request.QueryString["title"] ?? "")) 7 .Where(p => p.Author.Contains(Request.QueryString["author"] ?? "")); 8 9 var pageList=list.Skip((pageNumber - 1) * pageSize).Take(pageSize); 10 int total = list.Count(); 11 CustomPagination<News> customes = new CustomPagination<News>(pageList, pageNumber, pageSize, total); 12 13 return View(customes); 14 } 15 [AcceptVerbs(HttpVerbs.Post)] 16 public ActionResult CustomPager(FormCollection formCollection) 17 { 18 int pageSize = 3; 19 int pageNumber = 1; 20 var list = ListNews.GetList().Where(p => p.Title.Contains(Request.Form["title"])) 21 .Where(p => p.Author.Contains(Request.Form["author"])); 22 int total = list.Count(); 23 var pageList = list.Skip((pageNumber - 1) * pageSize).Take(pageSize); 24 CustomPagination<News> customes = new CustomPagination<News>(pageList, pageNumber, pageSize, total); 25 Dictionary<string, string> d = new Dictionary<string, string>(); 26 d.Add("title", Request.Form["title"]); 27 d.Add("author", Request.Form["author"]); 28 ViewData["Search"] = d; 29 return View(customes); 30 } |
注:这部分内容的详细讲解可以参见:ASP.NET MVC实践系列7-Grid实现(下-利用Contrib实现)
三、Contrib的分页源码分析
我们先把Pagination和Pager两个文件夹中的源码copy出来,经过分析我们知道CustomPagination是实现了IPagination接口的集合,我们把数据整合到CustomPagination中就可以使用Pager进行分页了,PaginationExtensions是辅助HtmlHelper使用扩展方法的静态类。