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?
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:
I would avoid the use of session anyway.
Note: don't forget to apply the POST - redirect - GET pattern after the confirmation!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With