EKsumic's Blog

let today = new Beginning();

Click the left button to use the catalog.

OR

X.PagedList.Mvc.Core的基本用法

前台index.cshtml添加:

@using X.PagedList.Mvc.Core;
@using X.PagedList;

<form action="~/Comments/Index" method="post">
    <p>
        Title: <input type="text" name="search" />
        <input type="submit" value="search" />
    </p>
</form>
……
@Html.PagedListPager((IPagedList)ViewBag.OnePageOfProducts, page => Url.Action("Index", new { page }))

后台Index方法(注意不要写[HttpPost]):

public async Task<IActionResult> Index(int? page, string search)
{
    var applicationDbContext = _context.Comments.OrderByDescending(x => x.PublishTime);

    if (search != null)
    {
        var products = applicationDbContext.Where(x => x.Name.Contains(search)); //returns IQueryable<Product> representing an unknown number of products. a thousand maybe?

        var pageNumber = page ?? 1; // if no page was specified in the querystring, default to the first page (1)
        var onePageOfProducts = products.ToPagedList(pageNumber, 10); // will only contain 25 products max because of the pageSize

        ViewBag.OnePageOfProducts = onePageOfProducts;
        return View(await onePageOfProducts.ToListAsync());

    }
    else
    {
        var products = applicationDbContext; //returns IQueryable<Product> representing an unknown number of products. a thousand maybe?

        var pageNumber = page ?? 1; // if no page was specified in the querystring, default to the first page (1)
        var onePageOfProducts = products.ToPagedList(pageNumber, 10); // will only contain 25 products max because of the pageSize

        ViewBag.OnePageOfProducts = onePageOfProducts;
        return View(await onePageOfProducts.ToListAsync());

    }
}

applicationDbContext是你取到的数据,你只需要改变x.Name的内容就可以实现根据x.xxxx的字段进行搜索,例如:x.Id、x.Content……

其它的代码除了数字10以外并不需要改动,默认是每页10条,你可以自己改成15条或20条。

This article was last edited at 2020-07-01 21:20:10

* *