Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping TempData for "just one more request..."

So, items in TempData are maintained in the session until they are read, after which they expire at the end of the current request.

This has the side-effect that refreshing a page using TempData will lose that data. In some situations (e.g. alerts), that's fine. In others (e.g. confirmation screens with cached view models) it's not. I have a confirmation screen which retrieves a model from TempData from the previous post:

public ActionResult Confirm()
{
    var model = TempData["model"];
    return View(model);
}

Pressing F5 breaks the confirmation screen. Now, I know I can keep hold of my TempData objects with either of the following, fixing the issue:

// Peek
var model = TempData.Peek("model");

// Keep
var model = TempData["model"];
TempData.Keep("model");

However, because the model is not read from TempData again after the next post, the cached model is now never removed (except in the normal circumstances in which a session variable is removed), negating the benefit of TempData.

Is there a way I can get a TempData key to persist for "just one more request," or am I limited to simply using Session and explicitly removing the key in the next request?

like image 434
Ant P Avatar asked Jan 23 '15 09:01

Ant P


1 Answers

Tempdata is made to keep state across a redirect. Hitting F5 is not a redirect, it's a page refresh, so yes, your data will be lost. So don't try to use TempDate for this purpose.

Alternatives:

  • Use output caching to cache your confirmation page on the client.
  • Use Cache to temporarily cache the page's data.
  • Store parameters as part of the URL.
  • Cookies

I would avoid the use of session anyway.

Note: don't forget to apply the POST - redirect - GET pattern after the confirmation!

like image 98
L-Four Avatar answered Oct 01 '22 06:10

L-Four