ASP.NET MVC中進行分頁的方式有多種,在NuGet上有提供使用PagedList、PagedList.Mvc進行分頁。css
1. 經過NuGet引用PagedList.Mvchtml
在安裝引用PagedList.Mvc的同時會安裝引用PagedList。spa
1.看一下Controller頁面的代碼,最後就簡單的一句,將List數據ToPagedList返回過去就能夠了。原來愛怎麼分頁能夠怎麼分頁。3d
//引用 using PagedList; namespace MvcApplication1.Controllers { public class SplitPageController : Controller { // // GET: /SplitPage/ public ActionResult Index(int page = 1) { //取數據 List<Package.Model.Message> lists = new List<Package.Model.Message>(); MessageDal message = new MessageDal(); DataSet ds = message.GetList(" 1=1 "); //轉成List for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { lists.Add(new Package.Model.Message() { gName = ds.Tables[0].Rows[i]["gName"].ToString(), gContent = ds.Tables[0].Rows[i]["gContent"].ToString() }); } //將數據分頁後返回頁面(這裏能夠在取數據的時候先分頁後,再使用ToPagedList實現分頁 return View( lists.ToPagedList(page, 2)); } } }
返回後在HTML頁面的顯示code
@model PagedList.IPagedList<Package.Model.Message> @using PagedList.Mvc; @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <table> <tr> <th> gname </th> <th> gContent </th> <th> </th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.gName) </td> <td> @Html.DisplayFor(modelItem => item.gContent) </td> <td></td> </tr> } </table> @Html.PagedListPager(Model, page => Url.Action("Index", new { page })) </body> </html>
使用ViewBag返回分頁數據,因爲MODEL只有一個,若是按官網給的例子,那麼一個頁面只能有一個分頁了,可是VIEWBAG點出來的卻能夠多個。htm
看一下顯示,很少說了,直接上代碼blog
CONTROLLER頁面it
using PagedList; namespace MvcApplication2.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index(int page = 1) { //取數據 List<Package.Model.Message> lists = new List<Package.Model.Message>(); MessageDal message = new MessageDal(); DataSet ds = message.GetList(" 1=1 "); //轉成List for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { lists.Add(new Package.Model.Message() { gName = ds.Tables[0].Rows[i]["gName"].ToString(), gContent = ds.Tables[0].Rows[i]["gContent"].ToString() }); } //將數據分頁後返回頁面(這裏能夠在取數據的時候先分頁後,再使用ToPagedList實現分頁 ViewBag.MyPageList = lists.ToPagedList(page, 2); return View( ); } } }
VIEW視圖io
@using PagedList.Mvc; @{ PagedList.IPagedList<Package.Model.Message> myPageList = (PagedList.IPagedList<Package.Model.Message>)ViewBag.MyPageList; Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <link href="~/Content/PagedList.css" rel="stylesheet" /> <title>Index</title> </head> <body> <table> <tr> <th> gname </th> <th> gContent </th> <th> </th> </tr> @foreach (var item in myPageList) { <tr> <td> @Html.DisplayFor(modelItem => item.gName) </td> <td> @Html.DisplayFor(modelItem => item.gContent) </td> <td></td> </tr> } </table> 每頁 @myPageList.PageSize 條記錄,共 @myPageList.PageCount 頁,當前第 @myPageList.PageNumber 頁 @Html.PagedListPager(myPageList, page => Url.Action("Index", new { page })) </body> </html>
參考這個原文:http://www.cnblogs.com/libingql/p/3486554.htmltable