There is a really cool jQuery tool (http://tablesorter.com/docs/index.html) that uses PFM Technology (Pure Freakin’ Magic) to make your html table just magically page and sort. It works great with MVC and nHibernate, but I wanted to get fancy and make my own. Turned out to be surprisingly easy. Here’s what I did:

Preparing the Controller

1. Create you search criteria:

ICriterion[] query = { Expression.Eq(FieldName, FieldValue) };

2. Get the total record count matching the criteria without actually pulling back all the records. I throw the count into a ViewData variable for later processing on the page:

int count = ActiveRecordMediator<listing>.Count(query);
ViewData["count"] = count;

3. Execute a SlicedFindAll search to only get the subset instead of the entire recordset.

Contact[] pagedContacts = Contact.SlicedFindAll((currentPageIndex) * Rows), Rows, query);

The currentPageIndex variable is passed in from the page. At this point, the controller is ready!

Preparing the View

1. First we will create links to the individual pages. This is also where we use the ViewData["count"] value:

int TotalListings = int.Parse(ViewData["count"].ToString());
int RecordsPerPage = 15;    // <-- this can be defined anywhere, I wired it for this demo
int TotalPages = (TotalListings + RecordsPerPage - 1) / RecordsPerPage;

StringBuilder sb = new StringBuilder();
if (TotalPages > 1)
{
for (int i = 0; i < TotalPages; i++)
{
sb.Append("<a href='/your-url-path/" + i.ToString() + "'>" + (i + 1).ToString() + "</a>&nbsp;&nbsp;");
}

Response.Write(sb.ToString());
}

2. Loop through your recordset, adding your rows.

3. Add an optional footer:

if (TotalPages > 1)
{
Response.Write(sb.ToString());
}

That’s it! This could easily be extended to include next, previous, etc. links, but for demo purposes this works well.