PaginatedList step by step
Step-1:
In my case, Retrieved all the dinners ORDER BY DinnerID in Index action. (Note: Order By is mandatory when you use Skip() and Take() method.)
public ActionResult Index(int Page = 0)
{
const int PageSize = 3;
var alldinners = DinnerRepository.FindAllFinners().OrderBy(d => d.DinnerID);
/* Some code */
}
Step-2:
Create PaginatedList class in the project root (eg: DinnerFinder\ PaginatedList.cs). In my case, DinnerFinder is my project name as the same time default namespace.
namespace DinnerFinder
{
public class PaginatedList<T>:List<T>
{
public int PageIndex { get; private set; }
public int PageSize { get; private set; }
public int PageCount { get; private set; }
public int TotalRec { get; private set; }
public PaginatedList(IQueryable<T> source, int pageIndex, int pageSize)
{
TotalRec = source.Count();
PageIndex = pageIndex;
PageSize = pageSize;
PageCount =(int) Math.Ceiling(TotalRec / (double)pageSize);
this.AddRange(source.Skip(pageIndex * pageSize).Take(pageSize));
}
public bool HasPreviousPage()
{
if (PageIndex > 0)
{
return true;
}
else
{
return false;
}
}
public bool HasNextPage()
{
if (PageIndex + 1 < PageCount)
{
return true;
}
else
{
return false;
}
}
}
}
Step-3:
Got to the Step-1 part write the following code in the âSome codeâ section.
var paginatedDinners = new PaginatedList<Dinner>( paginatedDinners, Page, PageSize);
return View("Index", paginatedDinners);
Now the Step-1 looks like as bellow.
public ActionResult Index(int Page = 0)
{
const int PageSize = 3;
var alldinners = DinnerRepository.FindAllFinners().OrderBy(d => d.DinnerID);
var paginatedDinners = new PaginatedList<Dinner>(alldinners, Page, PageSize);
return View("Index", paginatedDinners);
}
Step-4:
Got to the \Views\Dinners\Index.aspx file and update the following part of the code. I my case
Inherits="System.Web.Mvc.ViewPage<DinnerFinder.PaginatedList<DinnerFinder.Models.Din ner>>"
Instead of
Inherits="System.Web.Mvc.ViewPage<DinnerFinder.Models.Dinner>"
Where
DinnerFinder: is the project name/default namespace.
PaginatedList: is the pagination class created and stored in project root
ie. DinnerFinder\PaginatedList.cs
Step-5:
Add the following code snip same as book p-107
<% if (Model.HasPreviousPage) { %>
<%: Html.RouteLink(â<<<â, âPaiginationâ, new { page=(Model.PageIndex-1) }) %>
<% } %>
<% if (Model.HasNextPage) { %>
<%: Html.RouteLink(â>>>â,âPaiginationâ, new { page = (Model.PageIndex + 1) })%>
<% } %>
Note: âPaiginationâ is the new route name that you already created in Global.asax file. If not got to Global.asax and add the following code snip.
routes.MapRoute(
"Paigination",
"Dinners/Page/{page}", // URL with parameter
new { controller="Dinners",action="Index"}
);
Save and run.
Thanks
|