接下來講講PagedList套件的使用方式
在前面有提到Entity Framework 使用的方式 這邊以Day20資料庫為例這次使用Order作為範例
1.首先先去工具->NuGet套件管理員->管理方案NuGet套件->安裝PagedList.Mvc
2.新增一個PagedListController 並加入相關程式碼
using PagedList;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public class PagedListController : Controller
{
// GET: PagedList
private DBContext _db = new DBContext();
protected override void Dispose(bool disposing)
{
if (disposing)
{
_db.Dispose();
}
base.Dispose(disposing);
}
public ActionResult Index(int page = 1, int pageSize = 15)
{
var ListAll = from m in _db.Orders
select m;
var pagelist= ListAll.ToList().ToPagedList(page, pageSize);
return View(pagelist);
}
}
}
1.db 為連線資料庫
2.page 為第幾頁
3.pageSize 顯示幾筆資料
4.最上方需加入using PagedList
3.View的部分
@model IEnumerable<WebApplication1.Models.Order>
@using PagedList.Mvc;
@using PagedList;
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.CustomerID)
</th>
<th>
@Html.DisplayNameFor(model => model.EmployeeID)
</th>
<th>
@Html.DisplayNameFor(model => model.OrderDate)
</th>
<th>
@Html.DisplayNameFor(model => model.RequiredDate)
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.CustomerID)
</td>
<td>
@Html.DisplayFor(modelItem => item.EmployeeID)
</td>
<td>
@Html.DisplayFor(modelItem => item.OrderDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.RequiredDate)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.OrderID }) |
@Html.ActionLink("Details", "Details", new { id = item.OrderID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.OrderID })
</td>
</tr>
}
</table>
@Html.PagedListPager((IPagedList)Model, x => Url.Action("Index", new { page = x }))
1.上方需加入@using PagedList.Mvc、@using PagedList
2.最下方需加入@Html.PagedListPager
4.結果