【问题标题】:Using a paged list on model first approach?在模型优先方法上使用分页列表?
【发布时间】:2012-04-16 13:11:51
【问题描述】:

我想使用分页列表在我的视图中对数据进行分页,我之前使用网络网格进行过此操作,但发现使用模型优先方法很难做到这一点。非常感谢任何帮助。

谢谢

【问题讨论】:

    标签: visual-studio-2010 asp.net-mvc-3 controller paging pagedlist


    【解决方案1】:

    Steve Sanderson 在他的书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); }
       }
    }
    

    然后您可以根据需要使用此分页信息在视图中显示信息。

    【讨论】:

      【解决方案2】:

      在 github 上查看我的 PagedList nuget 包:

      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}))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-08
        • 2012-04-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多