id改成1,代表着从第一页开始查询
(一)controlles
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcApplication1.Models; namespace MvcApplication1.Controllusing { public class PagedCarController : Controller { private const int PAGESIZE = 3; public ActionResult Index(int id)//翻页 { int pageCount =new CarBF().GetPageCount(PAGESIZE); ViewBag.PageNo = id; ViewBag.PageCount = pageCount; List<int> pagelist = new List<int>(); for (int i = 1; i <= pageCount; i++) { pagelist.Add(i); } SelectList selectList = new SelectList(pagelist,id); ViewBag.PageList = selectList; List<Car> list = new CarBF().Select(PAGESIZE, id); return View(list); } } }
(二) models
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MvcApplication1.Models { public class CarBF { private MyDBDataContext _Context = new MyDBDataContext(); public List<Car> Select(int pageSize,int pageNo) //pageNo从1开始算的。 { var query = _Context.Car.Skip(pageSize * (pageNo - 1)).Take(pageSize); return query.ToList(); } public int GetPageCount(int pageSize) { int rowsCount = _Context.Car.Count(); int pageCount = (int)Math.Ceiling( 1.0* rowsCount / pageSize); return pageCount; } } }
(三 ) view
@using MvcApplication1.Models; @model List<Car> @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <script language="javascript"> function dochange() { var s = document.getElementById("pageid").value; var str = "new {id="+s+"}"; window.location.href = "/PagedCar/Index/" + s; } </script> </head> <body> <div> <ul> @foreach( Car data in Model ){ <li>@data.Name</li> } </ul> @{ int pageCount = (int)ViewBag.PageCount; int nowPage = (int)ViewBag.PageNo; int prevPage = nowPage - 1; int nextPage = nowPage + 1; } @Html.ActionLink("首页", "Index", "PagedCar", new { id=1},null) @Html.ActionLink("上一页", "Index", "PagedCar", new { id = prevPage }, new { onclick = (prevPage <= 0 ? "return false" : "return true") }) @Html.ActionLink("下一页", "Index", "PagedCar", new { id = nextPage }, new { onclick=(nextPage > pageCount?"return false;":"return true;" )}) @Html.ActionLink("尾页", "Index", "PagedCar", new { id = pageCount },null) 转向 @Html.DropDownList("pageid", ViewBag.PageList as SelectList, new { onchange="dochange()"}) 页 </div> </body> </html>
★ 最后一定要添加一个JS 的文件,否则无法正常运行。
效果图: