Just to state, as an alternative for those who want to learn how to do it in a simple way (not that PagedList
is not, it just does not reveal what it does underneath the cloths), just create a method that accept the current page and the quantity of items per page and use the methods Skip()
and Take()
of linq:
public IEnumerable<Clientes> ListarPagina(int paginaAtual, int itensPorPagina)
{
return contexto.Clientes.Skip((paginaAtual - 1) * itensPorPagina).Take(itensPorPagina).ToList();
}
If you want to assemble the paging links and have a specific ViewModel
with what you need to work, you can slightly modify the case and create a generic template for your paginated lists that accepts the total of records, page the number of items per page and the collection of items:
public class ListaPaginada<T>
{
public int TotalItens { get; private set; }
public int ItensPorPagina { get; private set; }
public int PaginaAtual { get; private set; }
public int TotalPaginas
{
get { return Math.Ceiling(TotalItens / ItensPorPagina); }
}
public List<T> Itens { get; private set; }
public ListaPaginada(List<T> itens, int totalItens, int itensPorPagina, int paginaAtual)
{
this.Itens = itens;
this.TotalItens = totalItens;
this.ItensPorPagina = itensPorPagina;
this.PaginaAtual = paginaAtual;
}
}
public ListaPaginada<Clientes> ListarPagina(int paginaAtual, int itensPorPagina)
{
var clientes = contexto.Clientes;
var totalClientes = clientes.Count();
var clientesDaPagina = clientes.Skip((paginaAtual - 1) * itensPorPagina).Take(itensPorPagina).ToList();
return new ListaPaginada<Clientes> (clientesDaPagina, totalClientes, itensPorPagina, paginaAtual);
}
In your view, you will have a single object with the properties to do the loops and generate the pagination and the list as desired:
@model ListaPaginada<Clientes>
if (Model.TotalItens > 0)
{
foreach(var item in Model.Itens)
{
<li>@item.Nome</li>
}
if (Model.TotalPaginas > 1)
{
<div class="paginacao">
@for(var i = 1; i < Model.TotalPaginas; i++)
{
Url.Action("Index", new { pagina = i })
}
</div>
}
}
else
{
<p>Nenhum item disponível no momento!</p>
}
I do not recommend replacing the component, I just present a way to do the same in a custom way, with good performance and probably what the component does underneath the cloths, without the unnecessary additions.