最小化Asp中的分页链接.净MVC

本文关键字:链接 MVC 分页 Asp 最小化 | 更新日期: 2023-09-27 18:05:41

我已经纠结了很长一段时间了。今天我终于写了下面的代码:

ViewModel包含一个int属性,该属性告诉视图数据被分成了多少页。

控制器通过获取指定数量的行来拆分数据,并且在分页的情况下,通过pageNumber * recordsPerPage

进行拆分

看一看:

ViewModel

public class ThreadPostsViewModel
{
    public Thread Thread { get; set; }
    public List<Post> Posts { get; set; }
    public int Pages { get; set; }
}

控制器

private int PostsPerPage = 10;
public ActionResult Thread(int id, int page = 1)
{
    using (OrtundEntities Db = new OrtundEntities())
    {
        // get the thread and its parent data (parent for breadcrumbs)
        var Thread = Db.Threads.Include(t => t.Title).FirstOrDefault(x => x.Id == id);
        // create a list for the Posts
        List<Post> Posts = new List<Post>();
        // select based on paging
        if (page == 1)
            // no paging has happened, get the first set of records
            Posts = Db.Posts.Include(x => x.User).Where(x => x.ThreadId == id).OrderByDescending(x => x.Date).Take(PostsPerPage).ToList();
        else
            // we're on a new page. Skip however many rows we've already seen
            Posts = Db.Posts.Include(x => x.User).Where( x=> x.ThreadId == id).OrderByDescending(x => x.Date).Take(PostsPerPage).Skip(PostsPerPage * page).ToList();
        // create and return the view model
        ThreadPostsViewModel Model = new ThreadPostsViewModel
        {
            Thread = Thread,
            Posts = Posts,
            Pages = Posts.Count / PostsPerPage
        };
        return View(Model);
    }
}

@model Ortund.Models.ThreadPostsViewModel
<div class="paging">
    @for (int i = 1; i < Model.Pages; i++)
    {
        string Url = String.Format("/View/Thread/{0}?page={1}", Model.Thread.Id, i);
        <a href="@Url">@i</a>
    }
</div>
<div class="posts-list">
    @foreach (var Post in Model.Posts)
    {
        <div class="post" id="@Post.Id">
        </div>
    }
</div>

在这段代码中,假设从数据库中选择了300篇文章,每个页面指定了10篇文章,那么应该有30个页面。

对于你的页面设计来说,这已经是一个巨大的链接量了,那么我如何才能最小化这些分页链接,比如只显示10个分页链接,而当你到达第8页时,链接会变成3-13个?

即使分页链接显示如下也是可取的:

1 2 3 4 5 ... 90 91 92 93 94

最小化Asp中的分页链接.净MVC

在控制器中设置当前页面的值:

ViewBag.currentPage = page;

考虑到你可以这样做(未测试):

<div class="paging">
@if (Model.Pages > 11 && ViewBag.currentPage > 6)
{
        for (int i = ViewBag.currentPage - 6; i < ViewBag.currentPage -1; i++)
        {
          string Url = String.Format("/View/Thread/{0}?page={1}", Model.Thread.Id, i);
          <a href="@Url">@i</a>
        }
        for (int i = ViewBag.currentPage + 1; i < ViewBag.currentPage + 6; i++)
        {
          string Url = String.Format("/View/Thread/{0}?page={1}", Model.Thread.Id, i);
          <a href="@Url">@i</a>
        }
}
else
{
        for (int i = 1; i < Model.Pages; i++)
        {
          string Url = String.Format("/View/Thread/{0}?page={1}", Model.Thread.Id, i);
          <a href="@Url">@i</a>
        }
}
</div>