【问题标题】:Adding unknown amount of pages to asp.net C# view将未知数量的页面添加到 asp.net C# 视图
【发布时间】:2018-10-14 08:05:37
【问题描述】:

我正在尝试使用 MVC 向 ASP.net Web 应用程序添加分页。目前我有一个控制器,它只是将数据库中的对象列表返回到视图。

 public ActionResult List()
    { 
        return View(db.Classes.ToList());
    }

在我看来,我正在访问数据以打印出所有项目,例如,

 @foreach (var i in Model)
{
    <div class="block">
        <a href="@Url.Action("Index", "Class", new { ClassID = (i.ClassID) })">
            <div class="classItem">
                <div class="title">
                    @Html.DisplayFor(Name => i.Name)
                </div>
                <div class="description">
                    @Html.DisplayFor(Description => i.Description)
                </div>
            </div>
        </a>
    </div>
    <br />
    <br />
</div>
}

我得到了一份不错的数据列表,但想知道如果项目数量超过一定数量,如何添加数据在页面中显示的功能?

【问题讨论】:

  • 有没有办法在不包含任何外部包的情况下做到这一点?
  • 您需要编写大量代码才能做到这一点。基本上无论图书馆做什么,你都必须自己做
  • 网上有很多分页的例子。您尝试过什么,遇到了什么具体问题?

标签: c# html asp.net asp.net-mvc pagination


【解决方案1】:

你试过 .Skip(N) 和 .Take(N)

private int pageLength = 10;

    public ActionResult List(int? page)
        { 
            var currentPage = page ?? 0;
            return View(db.Classes
                          .Skip(currentPage * pageLength)
                          .Take(pageLength)
                          .ToList());
        }

这是一个例子,你应该考虑 nullRef 和越界异常

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多