I want to do something like paging. Let’s suppose we have 100 contacts in our database. When my index page loads for the first time, it will load 20 contacts item from the database. There is a “more” button at the end of page. When user clicks that button, I want to load the next 20 items from the database and show them below the already displayed contacts.
public ActionResult Index(int no)
{
var contacts = GetContactFromDB(no) //no is used to know what is the current page number
}
public IList<Contact> GetContactFromDB(int pagenumber)
{
// here write the query to get next 20 items
}
I think one thing I forgot to tell is that I don’t want to loose the first 20. I mean that when the user clicks the button, the next next twenty contacts will be fetched from the database using an AJAX request and append those new 20 contacts after the previous ones…
Just use a combination of the
SkipandTakeextension methods from Linq:Note: This is not taking into account how you get
Contacts. But i guess you already know that 🙂 Also, it is assuming thatpageNumberis 0-based.If you are using Linq-To-SQL or Linq-To-Entities, the calls to
SkipandTakewill also be translated into a part of the final database query.