50
1
using System;
2
using System.Collections.Generic;
3
4
namespace PaginationExample
5
{
6
public class IndexViewModel
7
{
8
public IEnumerable<string> Items { get; set; }
9
public Pager Pager { get; set; }
10
}
11
12
public class Pager
13
{
14
public Pager(int totalItems, int? page, int pageSize = 10)
15
{
16
// calculate total, start and end pages
17
var totalPages = (int)Math.Ceiling((decimal)totalItems / (decimal)pageSize);
18
var currentPage = page != null ? (int)page : 1;
19
var startPage = currentPage - 5;
20
var endPage = currentPage + 4;
21
if (startPage <= 0)
22
{
23
endPage -= (startPage - 1);
24
startPage = 1;
66
<a href="http://jasonwatmore.com/post/2015/10/30/ASPNET-MVC-Pagination-Example-with-Logic-like-Google.aspx">ASP.NET MVC - Pagination Example with Logic like Google</a>
1
@model PaginationExample.IndexViewModel
2
3
<html>
4
<head>
5
<title>ASP.NET MVC - Pagination Example</title>
6
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
7
</head>
8
<body>
9
<div class="container">
10
<div class="col-md-6 col-md-offset-3">
11
<h1>ASP.NET MVC - Pagination Example</h1>
12
13
<!-- items being paged -->
14
<ul>
15
@foreach (var item in Model.Items)
16
{
17
<li>@item</li>
18
}
19
</ul>
20
21
<!-- pager -->
22
@if (Model.Pager.EndPage > 1)
23
{
24
<ul class="pagination">
25
1
using System;
2
using System.Web.Mvc;
3
using System.Collections.Generic;
4
using System.Linq;
5
6
namespace PaginationExample
7
{
8
public class HomeController : Controller
9
{
10
[HttpGet]
11
public ActionResult Index(int? page)
12
{
13
var dummyItems = Enumerable.Range(1, 150).Select(x => "Item " + x);
14
var pager = new Pager(dummyItems.Count(), page);
15
16
var viewModel = new IndexViewModel
17
{
18
Items = dummyItems.Skip((pager.CurrentPage - 1) * pager.PageSize).Take(pager.PageSize),
19
Pager = pager
20
};
21
22
return View(viewModel);
23
}
24
}
25
}