0

How can I get two value per get request from a List<>, For example, I have a Person List<> with six Person Ordered by ID in that List<> now in every get request using JQuery ajax() I want to get only two item from the list<>, first request will return Person with ID 1 & 2, second request will return Person with ID 3 & 4, and so forth.

I've tried

public IEnumerable<PersonViewModel> GetAllStudents()
    {
        IEnumerable<Person> dbPersons = _repo.getPersons().OrderBy(s => s.ID).Take(2);

        List<PersonViewModel> persons = new List<PersonViewModel>();
        foreach(var p in dbPersons)
        {
            persons.Add(MapDbPieToPersonViewModel(p));
        }

        return persons;
    }

But this only return first two item.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Sabir Hossain
  • 1,183
  • 1
  • 25
  • 46
  • 1
    Why would it ever return anything other than first two? You always take first two. Need to pass start point and skip to that – GraemeMiller Dec 14 '17 at 20:09
  • See https://stackoverflow.com/questions/2380413/paging-with-linq-for-objects – Jasen Dec 14 '17 at 20:13
  • And the more mvc-specific https://stackoverflow.com/questions/446196/how-do-i-do-pagination-in-asp-net-mvc – Jasen Dec 14 '17 at 20:16

1 Answers1

0

You should use Enumerable.Skip(Int32)

public IEnumerable<PersonViewModel> GetAllStudents(int page)
{
    const int PageSize = 2;
    IEnumerable<Person> dbPersons = _repo.getPersons().OrderBy(s => s.ID).Skip(page * PageSize).Take(PageSize);

    List<PersonViewModel> persons = new List<PersonViewModel>();
    foreach(var p in dbPersons)
    {
        persons.Add(MapDbPieToPersonViewModel(p));
    }

    return persons;
}
Albert
  • 601
  • 5
  • 14