回答

0

史蒂夫·桑德森介紹了他的書Pro ASP.NET MVC 3的的支持分頁例子,我強烈推薦(雖然直到下一個version發佈應該不會很長)。

他描述了產品控制器(上市的產品頁)爲:

public class ProductController : Controller { 
    public int PageSize = 4; //This could be retrieved from the database 

    private IProductRepository repository; 
    public ProductController(IProductRepository repoParam) { 
     repository = repoParam; 
    } 

    public ViewResult List(int page = 1) { 
     ProductsListViewModel viewModel = new ProductsListViewModel { 
     Products = repository.Products 
      .OrderBy(p => p.ProductID) 
      .Skip((page - 1) * PageSize) 
      .Take(PageSize), 
     PagingInfo = new PagingInfo { 
      CurrentPage = page, 
      ItemsPerPage = PageSize, 
      TotalItems = repository.Products.Count() 
     } 
     }; 
    return View(viewModel); 
} 

然後查詢到的動作可以是以下形式:

http://localhost:23081/Product/List?page=2 

(或任何路由您需要) 。

這個視圖模型將被:

public class ProductsListViewModel { 
    public IEnumerable<Product> Products { get; set; } 
    public PagingInfo PagingInfo { get; set; } 
} 

而且PagingInfo模型應該是:

public class PagingInfo { 
    public int TotalItems { get; set; } 
    public int ItemsPerPage { get; set; } 
    public int CurrentPage { get; set; } 
    public int TotalPages { 
     get { return (int)Math.Ceiling((decimal)TotalItems/ItemsPerPage); } 
    } 
} 

然後,您可以使用該尋呼信息按要求在視圖中顯示的信息。

0

看看我PagedList NuGet包在GitHub上:

https://github.com/troygoode/pagedlist

這將允許你寫的代碼如下所示:

MyController.cs

public class MyController : Controller{ 
    public object MyRoute(){ 
    var pagedProducts = ProductsRepo.All().ToPagedList(); 
    return View(pagedProducts); 
    } 
} 

MyRoute .cshtml

<ul> 
    @foreach(var product in ViewModel){ 
    <li>@product.Name</li> 
    } 
</ul> 
@Html.PagedListPager(ViewModel, page=> Url.Action("MyRoute", {page = page})) 
相關問題