David Clarke
David Clarke

Reputation: 13266

Persist querystring across requests in MVC 3

I have a page containing a list of clients with an ActionLink that allows the user to display (or hide) "inactive" clients. The showInactive=True is attached to the url as a querystring to the controller. Having displayed "inactive" clients I then edit one of them but when I save any changes or return to the list the querystring is gone. What is the best way to persist the querystring across those requests? I have tried the TempData dictionary but clearly I was attempting to use it for something it isn't designed to handle.

Upvotes: 3

Views: 5095

Answers (2)

Daniel Liuzzi
Daniel Liuzzi

Reputation: 17167

A simple way to achieve this is adding a returnUrl parameter to your action(s), like this:

[HttpPost]
public ActionResult Edit(int id, ClientEditModel model, string returnUrl)
{
    if (!ModelState.IsValid) return View();
    try
    {
        // do something
        return Redirect(returnUrl);
    }
    catch
    {
        return View();
    }
}

Then in your view, you call your action like so:

@Html.ActionLink("Edit", "Edit", new { id = Model.Id, returnUrl = Request.RawUrl })

In this setup, when the user is done editing, she is taken back to the same exact place she was before, persisting not just showInactive, but also any other parameters you might have in your list, such as page number, search criteria, sort order, etc.

Upvotes: 5

Khepri
Khepri

Reputation: 9627

Pass the querystring param on to your edit page and add the value as a hidden form field param. If it doesn't exist, default to false. This way when you perform your Edit post and do your processing you can pull the value out of your bound model/FormCollection/etc and based on it's value do a Redirect with the appropriate querystring param value.

return this.RedirectToAction("ListClients", new { showInactive = *INSERT THE VALUE* });

which translates to

/CurrentController/ListClients?showInactive=*value*

Upvotes: 1

Related Questions