views:

270

answers:

3

What is the best ASP.NET MVC pattern for paging data when the data is filtered by form criteria?

This question is similar to: http://stackoverflow.com/questions/1425000/preserve-data-in-net-mvc but surely there is a better answer?

Currently, when I click the search button this action is called:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Search(MemberSearchForm formSp, int? pageIndex, string sortExpression)
    {}

That is perfect for the initial display of the results in the table.

But I want to have page number links or sort expression links re-post the current form data (the user entered it the first time - persisted because it is returned as viewdata), along with extra route params 'pageIndex' or 'sortExpression',

Can an ActionLink or RouteLink (which I would use for page numbers) post the form to the url they specify?

<%= Html.RouteLink("page 2", "MemberSearch", new { pageIndex = 1 })%>

At the moment they just do a basic redirect and do not post the form values so the search page loads fresh.

In regular old web forms I used to persist the search params (MemberSearchForm) in the ViewState and have a GridView paging or sorting event reuse it.

+1  A: 

One possible solution is to attach a javascript click handler to the pager links that will submit the form by updating a hidden field containing the page number. This way you will get all the search criteria in the controller action.

Another possibility is to transform those pager links into submit buttons and place them inside the form.

A third possibility is to use the Session to persist search criteria.

Darin Dimitrov
Went with the first method and it works well. The only downside is the page functionality does not 'degrade gracefully' because it relies on JS. Will try the session way next time...
CRice
+1  A: 

You could perform a GET instead of a POST. if your request is to return search results, a GET might make more sense anyway. The benifit would be that all of your search fields are encoded into the URL. So, when you perform a page or sort on th exisiting URL, your data is perserved.

kim3er
+1  A: 

I have an example that using the MvcContrib Grid and Pager here:

http://weblogs.asp.net/rajbk/archive/2010/05/08/asp-net-mvc-paging-sorting-filtering-using-the-mvccontrib-grid-and-pager.aspx

Raj Kaimal
Thanks Raj, will check it out
CRice