views:

284

answers:

2

I am implementing a search module with result page support paging. The example provided by NerdDinner passes pagenumber as a parameter for the Index action, and the action uses the pagenumber to perform a query each time the user hit a different page number.

My problem is that my search take many more criteria such as price, material, model number etc. than just simple pagenumber. Therefore, I would like to preserve the criteria after users' first submission, so that I only have to pass the pagenumber back and forth.

Using ViewData is not possible because ViewData get cleared once it is sent to the View.

Is there any good way to preserve the criteria data as I wish?

+1  A: 

You pretty much have two ways to do this.

  1. Put the data that you want to preserve in a serializable session, cache or the database. Putting it in the database will be the safest choice but it will degrade your performance.

  2. You can store the preserved data in a hidden html tag. As long as the information is not sensitive this option should work well.

here is some supporting code. You can only use this within the same controller

public class questionController : Controller
{
    public QuestionFormData qdata;

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        qdata = (SerializationUtil.Deserialize(Request.Form["qdata"])
            ?? TempData["qdata"]
            ?? new QuestionFormData()) as QuestionFormData;
        TryUpdateModel(qdata);
    }

    protected override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        if (filterContext.Result is RedirectToRouteResult)
        {
            TempData["qdata"] = qdata;
        }
    }

Access the updated information like this

    public ActionResult Index()
    {
         DateTime d = qdata.date;
    }

In the aspx page

<%= Html.Hidden("qdata", SerializationUtil.Serialize(Model)) %>
@luke: I prefer #2 in my own work. @Wei Ma: Many people would argue it's better to pass the information back and forth repeatedly (it's not too hefty) rather than use Session, which carries with it its own challenges.
David Andres
Thanks Luke and David. I did not like to pass data back and forth between Controllers and Views. But David woke me up. After all, the size of data is not going to be more than a few hundreds bytes. Maybe not even as much as the http overhead.
Wei Ma
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