Get Your Paging Sorted

Why’s it so hard to build a paged list in ASP.NET MVC? Because paged lists typically need filtering and sorting and this simultaneous tracking of the current page number, filter criteria and sort order is no mean feat. If we’re not careful, we’ll lose the current sort order when clicking a paging Hyperlink or the filter criteria will be forgotten when clicking a sorting Hyperlink. The Navigation for ASP.NET project takes a new approach to managing data that makes it easy to build Hyperlinks that are amnesia-proof.

It’s In the Bag

With Navigation for ASP.NET we track our Url parameters in a data bag called NavigationData. At the start of each request this NavigationData is primed with all the Url’s Route and QueryString data. Clicking a paging Hyperlink, for example, would put the current page number into NavigationData.

When we build a Hyperlink we supply the new data and the Navigation project will combine this with the current NavigationData to create the Url. To build a sorting Hyperlink, we need only pass the new sort order and then the current page number held in NavigationData will be included. Paging Hyperlinks built in similar fashion will automatically remember the sort order.

	new NavigationData{{ "sortExpression", sortString }}, true)

But the filter criteria comes in as part of a posted HTML form and so isn’t loaded into NavigationData when the request begins. If it’s not part of the NavigationData then it won’t appear in our Hyperlinks and will be forgotten when paging or sorting. But unlike Route or QueryString data, NavigationData is writeable, allowing us to manually add in the filter criteria from our Controller code. Having made it into NavigationData, the filter criteria will be included in the paging and sorting Hyperlinks.

StateContext.Bag.filter = filterString;

Take a peek at my paging, sorting and filtering code sample to see how easy it is. If the Pager and Sorter method calls in the razor code look unfamiliar, rest assured that under the covers they both call to the RefreshLink extension method talked about here.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s