简体   繁体   中英

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. I've been searching far and wide but I only see pagination tutorials / entries using Entity Framework, ADO.Net, and the like.

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)

@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)

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; }

    }



}

I am facing this error:

错误

I am following this tutorial: 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 .

Below sample will skip first 10 rows and return next 5 rows.

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

If you use Sql server 2012+ you can use the new syntax

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

if you use sql server 2012- you need to use the old Row_Number function, which can be find here

MySql and Sqlite is much simple , it use limit offset and do not reqire order by

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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