MVC Pagination

****Model***

using System;
using System.Collections.Generic;

namespace PaginationExample
{
public class IndexViewModel
{
public IEnumerable Items { get; set; }
public Pager Pager { get; set; }
}

public class Pager
{
public Pager(int totalItems, int? page, int pageSize = 10)
{
// calculate total, start and end pages
var totalPages = (int)Math.Ceiling((decimal)totalItems / (decimal)pageSize);
var currentPage = page != null ? (int)page : 1;
var startPage = currentPage – 5;
var endPage = currentPage + 4;
if (startPage totalPages)
{
endPage = totalPages;
if (endPage > 10)
{
startPage = endPage – 9;
}
}

TotalItems = totalItems;
CurrentPage = currentPage;
PageSize = pageSize;
TotalPages = totalPages;
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; }
}
}

*** view ***
@model PaginationExample.IndexViewModel

ASP.NET MVC – Pagination Example

ASP.NET MVC – Pagination Example

    @foreach (var item in Model.Items)
    {

  • @item
  • }


@if (Model.Pager.EndPage > 1)
{

    @if (Model.Pager.CurrentPage > 1)
    {

  • First
  • Previous
  • }

    @for (var page = Model.Pager.StartPage; page <= Model.Pager.EndPage; page++)
    {

  • @page
  • }

    @if (Model.Pager.CurrentPage < Model.Pager.TotalPages)
    {

  • Next
  • Last
  • }

}


*** Controller ***
using System;
using System.Web.Mvc;
using System.Collections.Generic;
using System.Linq;

namespace PaginationExample
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index(int? page)
{
var dummyItems = Enumerable.Range(1, 150).Select(x => “Item ” + x);
var pager = new Pager(dummyItems.Count(), page);

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

return View(viewModel);
}
}
}

Copy From::
https://dotnetfiddle.net/Widget/eOe3tv

https://dotnetfiddle.net/eOe3tv

http://pramadha.com
http://shoessale.in

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s