关于c#:如何在ASP.NET Core中为服务器端分页编写代码

How to write code for Server side pagination in ASP.NET Core

我想实现服务器端分页,以加载一些我想加载到浏览器中的数据。在MVC中使用PageList可以很好地在客户端运行,但是我不知道如何在Asp.net Core Server端进行操作。

这是我的课程,我想显示所有比例,甚至是照片(图像)

1
2
3
4
5
6
7
8
9
10
public class HouseDTO
    {
        [Key]
        public int HouseId { get; set; }
        public Nullable<decimal> Price { get; set; }
        public string LiveArea { get; set; }
        public string RoomAmount { get; set; }
        public string HouseType { get; set; }
        public string ImageName { get; set; }
    }

然后是我的复活

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public interface IHouseRepository
{

  public IEnumerable<HouseDTO> GetAllHouses()

}

 public class HouseRepository : IHouseRepository
 {

    private ApplicationDbContext db;

    public HouseRepository(ApplicationDbContext db)
    {
            this.db = db;
    }

    public IEnumerable<HouseDTO> GetAllHouses()
    {
            return db.Houses;
    }
}

这是我的控制器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class AdvController : Controller
{

   private IHouseRepository db;
   private IHostingEnvironment hostingEnvirnment;

   public AdvController(IHouseRepository db, IHostingEnvironment hostingEnvirnment)
   {
      this.db = db;
      this.hostingEnvirnment = hostingEnvirnment;

   }

   public IActionResult Index()
   {
     var model = db.GetAllHouses();  // How can I do this to Server side pagination?
     return View(model);
   }
}

那么如何为该操作创建服务器端分页?

1
2
3
4
5
public IActionResult Index()
{
   var model = db.GetAllHouses();  
   return View(model);
}

如果您能帮助我,我将不胜感激。


您可以使用Skip()和Take()。制作一个存储库方法,该方法将采用当前位置(跳过)并将参数指定为Take。类似于:

1
2
3
4
public House GetPaged(currentPosition)
{
  return db.Houses.Skip(currentPosition).Take(20);
}


在db.Houses的结果上执行Take()和Skip()是方法。

赞:

1
2
3
4
5
// Skip (n) pages and take (x) elements from required page.
return db.Houses.Skip(page*countPerPage).Take(countPerPage);
// As suggested in comments for the answer above, specified code should belong to
// repository method. Initially implemented as a template to be copypasted
// and reused according to your needs.

确保查询中的页码从0开始:
如果未指定页面,则page = 0;否则,返回0。如果您需要页面#1,则页面= 0;否则,页面= 0。 page = 1(如果需要第2页等)。countPerPage的含义很明显:)