Web pagination with C #

2

I'm building an administrative application, and in this application I have a messaging page. I'm currently bringing the last 20 messages.

I already have the screen ready to receive this messages, but my problem is in making the button logic that show the next 20 messages, and so on.

//Mensagens Enviadas
        List<Mensagem> mensagens = this.mensagemServico.GetMany(l => l.LojaId == loja.LojaId && l.OrigemId != 0).OrderByDescending(l => l.DataEnvio).Take(20).ToList();
        mensagemModel.Mensagens = mensagens;

        return View(mensagemModel);

Basically this is my routine: it takes the last 20 messages sorted by date, and according to the source (Customer Source == 0)

What I would like to do is that when I click on "Next" it will bring the next 20.

I had the initial idea of saving to a model variable (I have a MensagemModel to return the value to View ) the amount already fetched from Messages, or current page to be able to have this control.

I'm a beginner so I have questions about how to pass some information between Views , such as Models , and how a pagination should be done.

If someone can help me, even if it's about the logic that should be followed to make this pagination, sorry to ask this kind of question but I do not want this pagination to be bad so I wanted your help, thank you.     

asked by anonymous 25.08.2016 / 16:34

2 answers

4

Another good option is to use one of the two components below:

Usage:

// Suponha int? pagina = null como argumento da Action.
var paginaNaoNula = pagina ?? 1;
List<Mensagem> mensagens = this.mensagemServico.GetMany(l => l.LojaId == loja.LojaId && l.OrigemId != 0).OrderByDescending(l => l.DataEnvio).ToPagedList(paginaNaoNula, 20);
mensagemModel.Mensagens = mensagens;

return View(mensagemModel);
    
25.08.2016 / 20:05
2

You have to use more method Skip

//Mensagens Enviadas
List<Mensagem> mensagens = this.mensagemServico.GetMany(l => l.LojaId == loja.LojaId && l.OrigemId != 0).OrderByDescending(l => l.DataEnvio)
.Skip(numberOfObjectsPerPage * pageNumber)
.Take(20).ToList();

mensagemModel.Mensagens = mensagens;

return View(mensagemModel);

The following code example demonstrates how to use Skip to skip a specified number of elements in a sorted array and returns the remaining elements.

int[] grades = { 59, 82, 70, 56, 92, 98, 85 };

IEnumerable<int> lowerGrades =
    grades.OrderByDescending(g => g).Skip(3);

Console.WriteLine("All grades except the top three are:");
foreach (int grade in lowerGrades)
{
    Console.WriteLine(grade);
}

/*
 This code produces the following output:

 All grades except the top three are:
 82
 70
 59
 56
*/
    
25.08.2016 / 18:01