Simple paging
Paging HtmlHelper
public static class PagingHelpers
{
public static MvcHtmlString PagingLinks(this HtmlHelper html,
PagingData pagingData,
Func<int, string> pageUrl)
{
var result = new StringBuilder();
for (int i = 1; i <= pagingData.TotalPages; i++)
{
var tag = new TagBuilder("a");
tag.MergeAttribute("href", pageUrl(i));
tag.InnerHtml = i.ToString(CultureInfo.InvariantCulture);
if (i == pagingData.CurrentPage)
tag.AddCssClass("selected");
result.Append(tag + " ");
}
return MvcHtmlString.Create(result.ToString());
}
}
View:
@Html.PagingLinks(Model.PagingData, x => Url.Action("Index", new { page = x }))
Controller:
public ActionResult Index(int page = 1)
{
IEnumerable<CountryModel> countryCollection = _context.CountryCollection;
var pagedModel = new PagedCountriesViewModel
{
Countries = countryCollection.OrderBy(p => p.Code)
.Skip((page - 1) * PageSize)
.Take(PageSize),
PagingData = new PagingData
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = countryCollection.Count()
}
};
return View(pagedModel);
}
Paging class:
public class PagingData
{
public int TotalItems { get; set; }
public int ItemsPerPage { get; set; }
public int CurrentPage { get; set; }
public int TotalPages
{
get { return (int)Math.Ceiling((decimal)TotalItems / ItemsPerPage); }
}
}