ASP.NET MVC第011天_查詢結果用PagedList分頁呈現
新增好MVC專案後
Models目錄下新準備好一個UserInfo的DTO Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MVC_PagedListTest.Models { public class UserInfo { public string Name { get; set; } public int Age { get; set; } public string Sex { get; set; } } } |
安裝Nuget套件PagedList.Mvc
https://github.com/TroyGoode/PagedList
程式部分
在HomeController.cs擴充一個顯示主要資料表格
跟一個做分頁切換的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | using MVC_PagedListTest.Models; using PagedList; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVC_PagedListTest.Controllers { public class HomeController : Controller { public ActionResult UsersList() { List<UserInfo> users = new List<UserInfo>(); Random random = new Random(); for (int idxUser = 0; idxUser < 100; idxUser++) { UserInfo userInfo = new UserInfo() { Name = "Jack" + (idxUser + 1).ToString(), Age = random.Next(23, 50), Sex = "男" }; users.Add(userInfo); } int idxPage = 1; int pageSize = 20; IPagedList<UserInfo> pageList = users.ToPagedList(idxPage, pageSize); return View(pageList); } public ActionResult PagerDetail(int page) { List<UserInfo> users = new List<UserInfo>(); Random random = new Random(); for (int idxUser = 0; idxUser < 100; idxUser++) { UserInfo userInfo = new UserInfo() { Name = "Jack" + (idxUser + 1 ).ToString(), Age = random.Next(23, 50), Sex = "男" }; users.Add(userInfo); } int pageindex = page; int pagesize = 10; IPagedList<UserInfo> plist = users.ToPagedList(pageindex, pagesize); return View("UsersList", plist); } //.... } } |
UsersList.cshtml檢視
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | @model PagedList.IPagedList<MVC_PagedListTest.Models.UserInfo> @using PagedList.Mvc @{ ViewBag.Title = "UsersList"; } <h2>UsersList</h2> <table class="table"> <tr> <th>姓名</th> <th>年齡</th> <th>性別</th> </tr> @foreach (var record in Model) { <tr> <td> @Html.DisplayFor(item => record.Name) </td> <td> @Html.DisplayFor(item => record.Age) </td> <td> @Html.DisplayFor(item => record.Sex) </td> </tr> } </table> 每頁 @Model.PageSize 筆資料,共 @Model.PageCount 頁,目前在第 @Model.PageNumber 頁 @Html.PagedListPager(Model, page => Url.Action("PagerDetail", new { page })) |
效果
留言
張貼留言