ASP.NET MVC 4 Controller + View ( Razor ) + Paging 方法
/App_Start/RouteConfig.cs |
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace MvcApplication { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); … … routes.MapRoute( name: "Home", url: "Home/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } } |
/Home/All ( /Views/Home/All.cshtml ) |
<table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <th>ID</th> <th>Category</th> <th>Sub Category</th> <th>Model</th> <th>Price</th> </tr> @foreach (var product in Model) { <tr> <td> <span> @Html.ActionLink(((int)product.id).ToString(), "Product", new { id = product.id.ToString() }) </span> </td> <td> <span> @product.cat </span> </td> <td> <span> @product.subcat </span> </td> <td> <span> @product.model </span> </td> <td> <span> @product.price </span> </td> </tr> } </table> <div style="width:1024px; margin-top:20px;"> @for (int i=1; i<=ViewBag.PageIndex; i++) { <span style="margin-right:4px;"> @Html.ActionLink(((int)i).ToString(), "All", new {id = i.ToString()}) </span> } </div> |
/Controller/HomeController.cs |
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcApplication.Controllers { public class HomeController : Controller { BITestEntities entity; … … public int getPageCount(int PageRecordCount, int TotalRecord) { float PageCount = ((float)TotalRecord / (float)PageRecordCount); if (PageCount.Equals(Math.Floor(PageCount))) return (int)PageCount; else return (int)(PageCount + 1); } public ActionResult All(int? id) { entity = new BITestEntities(); int PageRecordCount = 20; if (id.HasValue) { if (id < 1) id = 1; ViewBag.PageIndex = getPageCount(PageRecordCount, entity.ProductEntities.Count()); var DataModel = entity.ProductEntities.OrderBy(x => x.id).Skip(((int)(id – 1)) * PageRecordCount).Take(PageRecordCount).ToList(); return View(DataModel); } else { ViewBag.PageIndex = getPageCount(PageRecordCount, entity.ProductEntities.Count()); var DataModel = entity.ProductEntities.OrderBy(x => x.id).Take(PageRecordCount).ToList(); return View(DataModel); } } } } |