企業在做Asp.Net Mvc開發過程中,很多時候都是一些CRUD,最基本的就是一個列表頁面,然后附帶一些功能按鈕。如果有數據列表,大多數就會涉及到對數據進行分頁,這次就介紹一下Mvc PagedList控件分頁的使用方法。Github PagedList鏈接 。
下面我通過新建Mvc項目來展示PagedList的使用方法。
一、新建BookLibrary解決方案
確定后,選擇MVC
然后點擊確定。
二、添加PagedList與PagedList.Mvc的程序包。
選擇BookLibrary項目,鼠標右鍵選擇“管理NuGet程序包”,在瀏覽框中輸入PagedList.Mvc,選擇最新穩定版,我這里選擇4.5.0版本,點擊安裝,然后他會提示有依賴項
點擊確定,他會自動安裝PagedList與PagedList.Mvc程序包。同時看一下項目的Content文件夾,它會自動添加PagedList.css文件,這個是分頁控件的樣式表。
三、創建模型與上下文
1、創建Book模型類。
1 using System; 2 3 namespace BookLibrary.Models 4 { 5 public class Book 6 { 7 private Guid _Id; 8 9 public Guid Id 10 { 11 get { return _Id; } 12 set { _Id = value; } 13 } 14 15 private string _BookName; 16 17 public string BookName 18 { 19 get { return _BookName; } 20 set { _BookName = value; } 21 } 22 23 private decimal _Price; 24 25 public decimal Price 26 { 27 get { return _Price; } 28 set { _Price = value; } 29 } 30 31 private string _Author; 32 33 public string Author 34 { 35 get { return _Author; } 36 set { _Author = value; } 37 } 38 39 private int _Sort; 40 41 public int Sort 42 { 43 get { return _Sort; } 44 set { _Sort = value; } 45 } 46 47 } 48 }
2、通過管理NuGet程序包,添加EntityFramework程序包。
3、Web.config添加數據庫鏈接字符串
1 <connectionStrings> 2 <add name="BookConnection" connectionString="DataBase=|DataDirectory|\Book.mdf;Data Source=.;Initial Catalog=Book;UID=sa;PWD=123qwe;Integrated Security=True" providerName="System.Data.SqlClient"/> 3 </connectionStrings>
4、創建BookContext上下文類
1 using System.Data.Entity; 2 3 namespace BookLibrary.Models 4 { 5 public class BookContext : DbContext 6 { 7 public BookContext() : base("BookConnection") { } 8 public DbSet<Book> Books { get; set; } 9 } 10 }
四、創建數據庫初始化策略
在項目下新建DBInitializer文件夾,並新建BookInitializer類,使用數據庫初始化策略
CreateDatabaseIfNotExists<BookContext>,在Seed中添加一些數據
1 using System; 2 using System.Collections.Generic; 3 using System.Data.Entity; 4 using BookLibrary.Models; 5 6 namespace BookLibrary.DBInitializer 7 { 8 public class BookInitializer:CreateDatabaseIfNotExists<BookContext> 9 { 10 protected override void Seed(BookContext context) 11 { 12 var bookList = new List<Book>(); 13 for (int i = 0; i < 15; i++) 14 { 15 bookList.Add(new Book 16 { 17 Id = Guid.NewGuid(), 18 BookName = "你的善良必須有點鋒芒", 19 Author = "慕顏歌", 20 Price = 50, 21 Sort=i 22 }); 23 bookList.Add(new Book 24 { 25 Id = Guid.NewGuid(), 26 BookName = "月亮與六便士", 27 Author = "威廉.薩穆塞特.毛姆", 28 Price = 50, 29 Sort = i 30 }); 31 bookList.Add(new Book 32 { 33 Id = Guid.NewGuid(), 34 BookName = "將來的你,一定會感謝現在拼命的自己", 35 Author = "湯木", 36 Price = 50, 37 Sort = i 38 }); 39 bookList.Add(new Book 40 { 41 Id = Guid.NewGuid(), 42 BookName = "你只是看起來很努力", 43 Author = "李尚龍", 44 Price = 50, 45 Sort = i 46 }); 47 bookList.Add(new Book 48 { 49 Id = Guid.NewGuid(), 50 BookName = "人性的弱點", 51 Author = "戴爾.卡耐基", 52 Price = 50, 53 Sort = i 54 }); 55 bookList.Add(new Book 56 { 57 Id = Guid.NewGuid(), 58 BookName = "在痛苦的世界盡力而為", 59 Author = "俞敏洪", 60 Price = 50, 61 Sort = i 62 }); 63 bookList.Add(new Book 64 { 65 Id = Guid.NewGuid(), 66 BookName = "做最好的自己", 67 Author = "李開復", 68 Price = 50, 69 Sort = i 70 }); 71 bookList.Add(new Book 72 { 73 Id = Guid.NewGuid(), 74 BookName = "白夜行", 75 Author = "東野圭吾", 76 Price = 50, 77 Sort = i 78 }); 79 bookList.Add(new Book 80 { 81 Id = Guid.NewGuid(), 82 BookName = "活着", 83 Author = "余華", 84 Price = 50, 85 Sort = i 86 }); 87 bookList.Add(new Book 88 { 89 Id = Guid.NewGuid(), 90 BookName = "拆掉思維里的牆", 91 Author = "古典", 92 Price = 50, 93 Sort = i 94 }); 95 bookList.Add(new Book 96 { 97 Id = Guid.NewGuid(), 98 BookName = "巨流河", 99 Author = "齊邦媛", 100 Price = 50, 101 Sort = i 102 }); 103 } 104 context.Books.AddRange(bookList); 105 base.Seed(context); 106 } 107 } 108 }
在Web.config文件中entityFramework節點下添加如下配置
1 <contexts> 2 <context type="BookLibrary.Models.BookContext,BookLibrary"> 3 <databaseInitializer type="BookLibrary.DBInitializer.BookInitializer,BookLibrary"></databaseInitializer> 4 </context> 5 </contexts>
五、創建控制器與視圖
新建BookController控制器
1 using PagedList; 2 using System.Configuration; 3 using System.Linq; 4 using System.Web.Mvc; 5 using BookLibrary.Models; 6 7 namespace BookLibrary.Controllers 8 { 9 public class BookController : Controller 10 { 11 /// <summary> 12 /// 數據庫上下文 13 /// </summary> 14 private BookContext db; 15 public BookController() 16 { 17 db = new BookContext(); 18 } 19 20 // GET: Book 21 public ActionResult Index(int? page) 22 { 23 ///書籍列表 24 var books = db.Books.OrderByDescending(p => p.Sort); 25 26 27 ///page為null時默認設置為1 28 var pageNumber = page ?? 1; 29 30 ///每頁顯示項目數量 31 var pageSize = 10; 32 if (ConfigurationManager.AppSettings["PageSize"] != null) 33 { 34 int.TryParse(ConfigurationManager.AppSettings["PageSize"], out pageSize); 35 } 36 37 38 ///進行分頁生成model 39 IPagedList<Book> model = books.ToPagedList(pageNumber, pageSize); 40 41 return View(model); 42 } 43 } 44 }
創建視圖
1 @model PagedList.IPagedList<BookLibrary.Models.Book> 2 @using PagedList.Mvc; 3 @{ 4 ViewBag.Title = "書籍列表"; 5 } 6 <link href="~/Content/PagedList.css" rel=" stylesheet" /> 7 <h2>@ViewBag.Title</h2> 8 <style> 9 .highLight { 10 } 11 12 .highLight > a { 13 background-color: #dc6969 !important; 14 color: #ffffff !important; 15 font-weight: 500; 16 font-family: '黑體'; 17 /*font-size:15px;*/ 18 } 19 </style> 20 <table class="table"> 21 <thead> 22 <tr> 23 <th> 24 書名 25 </th> 26 <th> 27 作者 28 </th> 29 <th> 30 價格 31 </th> 32 </tr> 33 </thead> 34 <tbody> 35 @if (Model != null && Model.Count > 0) 36 { 37 foreach (var book in Model) 38 { 39 <tr> 40 <td>@Html.DisplayFor(p => book.BookName)</td> 41 <td>@Html.DisplayFor(p => book.Author)</td> 42 <td>@Html.DisplayFor(p => book.Price)元</td> 43 </tr> 44 } 45 46 } 47 else 48 { 49 <tr><td colspan="3">---</td></tr> 50 } 51 52 </tbody> 53 </table> 54 @Html.PagedListPager(Model, page => Url.Action("Index", "Book", new { page = page }), new PagedListRenderOptions 55 { 56 DisplayItemSliceAndTotal = true, 57 Display = PagedListDisplayMode.IfNeeded, 58 ItemSliceAndTotalFormat = "顯示{0}頁到{1}頁,共{2}條", 59 //LinkToNextPageFormat = "»", 60 LinkToNextPageFormat = ">>", 61 LinkToLastPageFormat = "Last", 62 DisplayLinkToLastPage = PagedListDisplayMode.Always, 63 LinkToFirstPageFormat = "First", 64 DisplayLinkToFirstPage = PagedListDisplayMode.Always, 65 LinkToPreviousPageFormat = "<<", 66 // LinkToPreviousPageFormat = "«", 67 DisplayEllipsesWhenNotShowingAllPageNumbers = true, 68 DisplayPageCountAndCurrentLocation = true, 69 PageCountAndCurrentLocationFormat = "當前第{0}頁,共{1}頁", 70 ClassToApplyToLastListItemInPager = "highLight", 71 ClassToApplyToFirstListItemInPager = "highLight", 72 LiElementClasses = new List<string> { "highLight" } 73 74 })
最終的項目結構如下
然后運行項目,輸入控制器名字/Book,最終效果如下
如果自己要更改分頁樣式的話,可以看一下PagedListRenderOptions這個類,配置還是很靈活的。
六、無刷新分頁
上面的分頁是刷新分頁,那這個插件有沒有更厲害一點的呢,實現無刷新分頁呢,下面我們來看一下這個類PagedListRenderOptions的介紹
很幸運,這個類PagedListRenderOptions有三個靜態方法,我們從靜態方法名字上可以大概讀出的意思是“啟用不引人注目的Ajax替換”請忽略我的翻譯,哈哈,其實大概意思就是無刷新的方式,下面我們就使用這個來實現無刷新的分頁。
1、首先看一下你的項目文件夾Scripts目錄下是否含有”jquery.unobtrusive-ajax.js“這個腳本
因為無刷新分頁需要用到這個腳本,如果沒有可以通過 管理NuGet程序包/程序包管理控制台 的形式進行添加,在瀏覽框中輸入
”Microsoft.Jquery.Unobtrusive.Ajax“
然后點擊安裝,我這里已經安裝完成。
2、在BookController中添加一個名字為Info的ActionResult,代碼內容如下
1 public ActionResult Info(int? page, bool jqueryUnobtrusive = false) 2 { 3 ///書籍列表 4 var books = db.Books.OrderByDescending(p => p.Sort); 5 6 ///page為null時默認設置為1 7 var pageNumber = page ?? 1; 8 9 ///每頁顯示項目數量 10 var pageSize = 10; 11 if (ConfigurationManager.AppSettings["PageSize"] != null) 12 { 13 int.TryParse(ConfigurationManager.AppSettings["PageSize"], out pageSize); 14 } 15 16 ///進行分頁生成model 17 IPagedList<Book> model = books.ToPagedList(pageNumber, pageSize); 18 19 ViewBag.jqueryUnobtrusive = jqueryUnobtrusive; 20 return View(model); 21 }
3、然后創建視圖Info.cshtml,代碼內容如下
1 @model PagedList.IPagedList<BookLibrary.Models.Book> 2 @using PagedList.Mvc; 3 @{ 4 if (ViewBag.jqueryUnobtrusive == true) 5 { 6 Layout = null; 7 } 8 ViewBag.Title = "書籍列表"; 9 } 10 @section scripts{ 11 <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"></script> 12 } 13 <div id="bookListAjax"> 14 <link href="~/Content/PagedList.css" rel=" stylesheet" /> 15 <style> 16 .highLight { 17 } 18 19 .highLight > a { 20 background-color: #dc6969 !important; 21 color: #ffffff !important; 22 font-weight: 500; 23 font-family: '黑體'; 24 /*font-size:15px;*/ 25 } 26 </style> 27 <h2>@ViewBag.Title</h2> 28 <table class="table"> 29 <thead> 30 <tr> 31 <th> 32 書名 33 </th> 34 <th> 35 作者 36 </th> 37 <th> 38 價格 39 </th> 40 </tr> 41 </thead> 42 <tbody> 43 @if (Model != null && Model.Count > 0) 44 { 45 foreach (var book in Model) 46 { 47 <tr> 48 <td>@Html.DisplayFor(p => book.BookName)</td> 49 <td>@Html.DisplayFor(p => book.Author)</td> 50 <td>@Html.DisplayFor(p => book.Price)元</td> 51 </tr> 52 } 53 54 } 55 else 56 { 57 <tr><td colspan="3">---</td></tr> 58 } 59 60 </tbody> 61 </table> 62 @Html.PagedListPager(Model, page => Url.Action("Info", "Book", new { page = page, jqueryUnobtrusive = true }), PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new PagedListRenderOptions 63 { 64 DisplayItemSliceAndTotal = true, 65 Display = PagedListDisplayMode.IfNeeded, 66 ItemSliceAndTotalFormat = "顯示{0}頁到{1}頁,共{2}條", 67 //LinkToNextPageFormat = "»", 68 LinkToNextPageFormat = ">>", 69 LinkToLastPageFormat = "Last", 70 DisplayLinkToLastPage = PagedListDisplayMode.Always, 71 LinkToFirstPageFormat = "First", 72 DisplayLinkToFirstPage = PagedListDisplayMode.Always, 73 LinkToPreviousPageFormat = "<<", 74 // LinkToPreviousPageFormat = "«", 75 DisplayEllipsesWhenNotShowingAllPageNumbers = true, 76 DisplayPageCountAndCurrentLocation = true, 77 PageCountAndCurrentLocationFormat = "當前第{0}頁,共{1}頁", 78 ClassToApplyToLastListItemInPager = "highLight", 79 ClassToApplyToFirstListItemInPager = "highLight", 80 LiElementClasses = new List<string> { "highLight" } 81 }, new AjaxOptions 82 { 83 AllowCache = false, 84 UpdateTargetId = "bookListAjax", 85 HttpMethod = "Post" 86 })) 87 </div>
需要注意的地方
1、BookController控制器的Info方法,添加一個默認參數jqueryUnobtrusive=false用來區別是第一次加載還是通過Ajax的方式訪問
2、Info.cshtml中通過ViewBag.jqueryUnobtrusive來判斷是否使用Layout模板
3、使用@section scripts方式添加jquery.unobtrusive-ajax.js腳本
最后看一下效果圖