4

.NET Core 2.1 MVC 实现 PagedList

 3 years ago
source link: https://azhuge233.com/net-core-2-1-mvc-%e5%ae%9e%e7%8e%b0-pagedlist/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

.NET Core 2.1 MVC 实现 PagedList

  • .NET Core 2.1
  • NuGet 包管理器
  • 开源分页包 Sakura.AspNetCore.Mvc.PageList Sakura.AspNetCore.PagedList.NET Core 2.1 MVC 实现 PagedList
  1. NuGet中安装上述两个包(只安装一个无法使用)。
  2. 编辑Startup.cs的ConfigureServices方法。
    • 添加默认的bootstrap式的分页实现(原文:“Add default bootstrap-styled pager implementation”)
      public void ConfigureServices(IServiceCollection services)
      // .. Other configuration codes in you application
      // Add default bootstrap-styled pager implementation
      services.AddBootstrapPagerGenerator(options =>
      // Use default pager options.
      options.ConfigureDefault();
      public void ConfigureServices(IServiceCollection services)
      {
        // .. Other configuration codes in you application
       
        // Add default bootstrap-styled pager implementation
        services.AddBootstrapPagerGenerator(options =>
        {
          // Use default pager options.
          options.ConfigureDefault();
         });
      }
  3. 编辑_ViewImports.cs,加入以下代码,对所有视图应用pager标签。
    @addTagHelper *, Sakura.AspNetCore.Mvc.PagedList
    @addTagHelper *, Sakura.AspNetCore.Mvc.PagedList
  1. 假设我们已经拿到了一些数据,需要分页展示在视图中。
    • 数据必须是IEnumerable<T> 或者 IQueryable<T>类型,这样才能将其转换为PagedList类型
  2. 先在控制器中将数据转换为PagedList类型,然后返回到视图中。
    var pagedata = Staffs.ToPagedList(pageSize, page);
    return View(pagedata);
    var pagedata = Staffs.ToPagedList(pageSize, page);
    return View(pagedata);
    • 其中,pageSize是每一页的条目数,page是起始页
  3. 修改视图控制器,在方法内加入页面参数page,指定展示第几页。
    public IActionResult Search(int page = 1) {
    ... ...
    public IActionResult Search(int page = 1) {
        ... ...
    }
    • 这里的参数page就是上一步转换类型时传入的起始页数page
  4. 在视图中添加分页模型。
    @model Sakura.AspNetCore.IPagedList<your.Model>
    @model Sakura.AspNetCore.IPagedList<your.Model>
  5. 循环输出模型中的数据。
    @foreach (var i in Model) {
    <tr>
    <td>@i.snum</td>
    ... ...
    </tr>
    @foreach (var i in Model) {
    <tr>
        <td>@i.snum</td>
        ... ...
    </tr>
    }
  6. 最后在视图中添加pager标签。
    <pager source="yourModel" />
    <pager source="yourModel" />
    • 这里的source模型类型必须为IPagedList,并且不需要添加‘@’前缀(原文:“The “source” attribute must be a C# expression with return type of `IPagedList` (no “@” perfix is needed)”)
    • 指南中还提供了未指定source的pager使用方法,用来建立静态的分页页面

.NET Core 2.1 MVC 实现 PagedList


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK