【问题标题】:How to do pagination in C# / MVC without Entity Framework?如何在没有实体框架的 C#/MVC 中进行分页?
【发布时间】:2020-04-28 02:38:48
【问题描述】:

正如标题所说,没有实体框架如何进行分页?我在没有实体框架的情况下创建了我的数据库,它只涉及 DLL 库。我一直在广泛搜索,但我只看到使用 Entity Framework、ADO.Net 等的分页教程/条目。

非常感谢您!

编辑:

非常感谢您的回答。更具体地说,我现在将展示我的代码:

List.cshtml(视图)

@model IEnumerable<OverTime.Models.UserModel>

@{
    ViewBag.Title = "List of Users";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>List of Users</h2>

<p>
    @Html.ActionLink("Add User", "CreateUser")
</p>
<body>
    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.username)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.email)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.password)
            </th>
            <th></th>
        </tr>

        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.username)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.email)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.password)
                </td>
                <td>
                    @Html.ActionLink("Edit", "EditUser", new { id = item.usr_Id }) |
                    @Html.ActionLink("Details", "Details", new { id = item.usr_Id }) |
                    @Html.ActionLink("Delete", "DeleteUser", new { id = item.usr_Id })
                </td>
            </tr>
        }



    </table>

    @if (Model.Pager.EndPage > 1)
    {
        <ul class="pagination">
            @if (Model.Pager.CurrentPage > 1)
            {
                <li>
                    <a href="~/Home/Index">First</a>
                </li>
                <li>
                    <a href="~/Home/List?page=@(Model.Pager.CurrentPage - 1)">Previous</a>
                </li>
            }

            @for (var page = Model.Pager.StartPage; page <= Model.Pager.EndPage; page++)
            {
                <li class="@(page == Model.Pager.CurrentPage ? "active" : "")">
                    <a href="~/Home/List?page=@page">@page</a>
                </li>
            }

            @if (Model.Pager.CurrentPage < Model.Pager.TotalPages)
            {
                <li>
                    <a href="~/Home/List?page=@(Model.Pager.CurrentPage + 1)">Next</a>
                </li>
                <li>
                    <a href="~/Home/List?page=@(Model.Pager.TotalPages)">Last</a>
                </li>
            }
        </ul>
    }
</body>

UserController.cs(控制器)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OT_lib.Interfaces;
using OT_lib.BusinessLayer;
using OT_lib.Entity;
using OverTime.Models;
using PagedList;


namespace OverTime.Controllers
{
    public class UserController : Controller {

        [HttpGet]
        public ActionResult Pagination(int? page)
        {
            var dummyItems = Enumerable.Range(1, 150).Select(x => "Items" + x);
            var pager = new Pager(dummyItems.Count(), page);

            var viewModel = new UserModel()
            {
                Items = dummyItems.Skip((pager.CurrentPage - 1) * pager.PageSize).Take(pager.PageSize),
                Pager = pager
            };

            return View(viewModel);
        }

        public ActionResult List(UserModel usermodel)
        {
            //UserBusinessLayer userService = new UserBusinessLayer("sqlconn");

            IUserInterface userService = new UserBusinessLayer("sqlConn");
            List<UserEntity> list = userService.GetAllUsers();
            List<UserModel> listModel = new List<UserModel>();

            foreach (var item in list)
            {
                listModel.Add(new UserModel()
                {
                    email = item.email,
                    password = item.password,
                    username = item.username,
                    usr_Id = item.usr_Id

                });
            }
            return View(listModel);
        }

        public ActionResult CreateUser()
        {
            return View();
        }

        [HttpPost]
        public ActionResult CreateUser(UserModel userModel)
        {
            //UserBusinessLayer userService = new UserBusinessLayer("sqlConn");

            IUserInterface userService = new UserBusinessLayer("sqlConn");

            userService.CreateUser(new UserEntity()
            {
                username = userModel.username,
                email = userModel.email,
                password = userModel.password
            });

            return RedirectToAction("List");
        }

        public ActionResult EditUser(int id)
        {
            //UserBusinessLayer userService = new UserBusinessLayer("sqlconn");

            IUserInterface userService = new UserBusinessLayer("sqlConn");

            UserModel userModel = new UserModel();

            try
            {
                UserEntity userEntity = userService.GetUserId(id);

                userModel.usr_Id = userEntity.usr_Id;
                userModel.email = userEntity.email;
                userModel.username = userEntity.username;
                userModel.password = userEntity.password;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return View(userModel);
        }

         //Update user info
        [HttpPost]
        public ActionResult EditUser(UserModel userModel)
        {
            //UserBusinessLayer userService = new UserBusinessLayer("sqlConn");

            IUserInterface userService = new UserBusinessLayer("sqlConn");

            userService.EditUser(new UserEntity()
            {
                   usr_Id = userModel.usr_Id,
                   username = userModel.username,
                   email = userModel.email,
                   password = userModel.password
            });

            return RedirectToAction("List");
        }

        public ActionResult DeleteUser(int id)
        {
            //UserBusinessLayer userService = new UserBusinessLayer("sqlconn");
            IUserInterface userService = new UserBusinessLayer("sqlConn");

            UserModel userModel = new UserModel();

            try
            {
                UserEntity userEntity = userService.GetUserId(id);

                userModel.usr_Id = userEntity.usr_Id;
                userModel.email = userEntity.email;
                userModel.username = userEntity.username;
                userModel.password = userEntity.password;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return View(userModel);
        }

        [HttpPost, ActionName("DeleteUser")]
        public ActionResult DeleteUserConfirmed(int id)
        {
            //UserBusinessLayer userService = new UserBusinessLayer("sqlconn");
            IUserInterface userService = new UserBusinessLayer("sqlConn");

            try
            {
                userService.DeleteUser(id);
            }
            catch (Exception eDelete)
            {
                throw eDelete;
            }

            return RedirectToAction("List");
        }

        public ActionResult Details(int id)
        {
            //UserBusinessLayer userService = new UserBusinessLayer("sqlconn");
            IUserInterface userService = new UserBusinessLayer("sqlConn");

            UserModel userModel = new UserModel();

            try
            {
                UserEntity userEntity = userService.GetUserId(id);

                userModel.usr_Id = userEntity.usr_Id;
                userModel.email = userEntity.email;
                userModel.username = userEntity.username;
                userModel.password = userEntity.password;

            }
            catch (Exception ex)
            {
                throw ex;
            }

            return View(userModel);
        }
    }
}

UserModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace OverTime.Models
{
    public class UserModel
    {
        public IEnumerable<string> Items { get; set; }
        public Pager Pager { get; set; }

        public int usr_Id { get; set; }

        [Display(Name = "Username")]
        [Required(ErrorMessage="Username is required")]
        [RegularExpression(@"^[a-zA-Z0-9]+$", ErrorMessage = "user name must be combination of letters and numbers only.")]
        public string username { get; set; }

        [Display(Name = "Email")]
        [Required(ErrorMessage = "Email is required")]
        [EmailAddress(ErrorMessage="Invalid email address")]
        public string email { get; set; }

        [Display(Name = "Password")]
        [Required(ErrorMessage = "Password is required")]
        [Remote("CheckEmail", "Account")]
        public string password { get; set; }

        [Display(Name = "Confirm Password")]
        [Required(ErrorMessage = "Confirmation of password is required")]
        //[Compare("password", ErrorMessage="Passwords do not match")]
        public string confirmPassword { get; set; }
    }

    public  class Pager
    {
        public Pager(int totalItems, int? page, int pageSize = 10)
        {
            var totalPage = (int)Math.Ceiling((decimal)totalItems / (decimal)pageSize);
            var currentPage = page != null ? (int)page : 1;
            var startPage = currentPage - 5;
            var endPage = currentPage + 4;

            if (startPage <= 0)
            {
                endPage -= (startPage - 1);
                startPage = 1;
            }
            if (endPage > totalPage)
            {
                endPage = totalPage;

                if (endPage > 10)
                {
                    startPage = endPage - 9;
                }
            }

            TotalItems = totalItems;
            CurrentPage = currentPage;
            PageSize = pageSize;
            TotalPages = totalPage;
            StartPage = startPage;
            EndPage = endPage;

        }

        public int TotalItems { get; private set; }
        public int CurrentPage { get; private set; }
        public int PageSize { get; private set; }
        public int TotalPages { get; private set; }
        public int StartPage { get; private set; }
        public int EndPage { get; private set; }

    }



}

我正面临这个错误:

我正在关注本教程:ASP.NET MVC - Pagination Example with Logic like Google

我该怎么办?再次提前感谢您!

【问题讨论】:

  • 你使用什么数据库?
  • I made my database without Entity Framework, and it involves just DLL libraries - 你能展示一些工作代码来说明这一点吗?此外,了解它需要扩展多少也会很有帮助。您可以使用IEnumerable&lt;T&gt; 以及 LINQ 的SkipTake 方法(例如使用List&lt;T&gt;)非常轻松地进行分页,但是要使其扩展,您需要某种基础架构来确保仅来自所需的页面实际上已加载到 RAM 中。
  • 请阅读How to create a Minimal, Complete, and Verifiable example - 99% 的代码与您的问题无关
  • 这与我在没有实体框架的情况下创建分页的尝试直接相关,因为我不使用 EF,但我现在遇到错误。请协助我如何正确编辑/攻击这个问题。谢谢!
  • @NightOwl888 我更新了我的帖子。请查找已编辑的部分。非常感谢!

标签: c# asp.net-mvc pagination


【解决方案1】:

如果你使用 Sql server 2012+,你可以使用新语法

SELECT * FROM tb ORDER BY id DESC OFFSET {pagesize * pageIndex} ROWS FETCH NEXT { pagesize } ROWS ONLY

注意:order by是必需的,{ }不是sql,它是你应该提供的变量

如果你使用sql server 2012-你需要使用旧的Row_Number函数,可以找到here

MySql 和 Sqlite 很简单,它使用limit offset,不需要order by

【讨论】:

  • 我更新了我的帖子。请查找已编辑的部分。非常感谢!
【解决方案2】:

如果您使用 SQL Server 2012,则可以使用 OFFSETFETCH

以下示例将跳过前 10 行并返回接下来的 5 行。

SELECT First Name + ' ' + Last Name 
FROM Employees 
ORDER BY First Name 
OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY;

https://technet.microsoft.com/en-us/library/gg699618(v=sql.110).aspx

【讨论】:

  • 我更新了我的帖子。请查找已编辑的部分。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-23
  • 2012-04-26
  • 2020-04-12
  • 1970-01-01
  • 2020-04-13
  • 2011-12-06
  • 1970-01-01
相关资源
最近更新 更多