简体   繁体   English

如何在没有实体框架的 C#/MVC 中进行分页?

[英]How to do pagination in C# / MVC without Entity Framework?

As the title says, how can I have a pagination without Entity Framework?正如标题所说,如果没有实体框架,我如何进行分页? I made my database without Entity Framework, and it involves just DLL libraries.我在没有实体框架的情况下创建了我的数据库,它只涉及 DLL 库。 I've been searching far and wide but I only see pagination tutorials / entries using Entity Framework, ADO.Net, and the like.我一直在广泛搜索,但我只看到使用 Entity Framework、ADO.Net 等的分页教程/条目。

Thank you very much in advance!非常感谢您提前!

EDIT:编辑:

Thank you very much for your answers.非常感谢您的回答。 To be more specific, I will show my code right now:更具体地说,我现在将展示我的代码:

List.cshtml(view) 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 (Controller) 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用户模型.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; }

    }



}

I am facing this error:我正面临这个错误:

错误

I am following this tutorial: ASP.NET MVC - Pagination Example with Logic like Google我正在学习本教程: ASP.NET MVC - Pagination Example with Logic like Google

What should I do?我该怎么办? Thank you once again in advance!再次感谢您!

If you use SQL Server 2012, then you can use OFFSET and FETCH .如果您使用 SQL Server 2012,则可以使用OFFSETFETCH

Below sample will skip first 10 rows and return next 5 rows.下面的示例将跳过前 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 https://technet.microsoft.com/en-us/library/gg699618(v=sql.110).aspx

If you use Sql server 2012+ you can use the new syntax如果您使用 Sql server 2012+,则可以使用新语法

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

note : order by is required , the { } is not sql ,it is the variable you shoud provide注意: order by是必需的, { }不是 sql,它是您应该提供的变量

if you use sql server 2012- you need to use the old Row_Number function, which can be find here如果您使用 sql server 2012-您需要使用旧的Row_Number函数,可以在这里找到

MySql and Sqlite is much simple , it use limit offset and do not reqire order by MySql 和 Sqlite 非常简单,它使用limit offset并且不要求order by

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM