Search code examples
c#asp.net-mvctempdata

ASP.NET MVC: reassign TempData


In a controller action I receive a variable from a redirect in a TempData variable

public ActionResult ChangePassword()
{
    string t = (string)TempData["myVariable"]; // works ok when coming from the redirect
    [..]
}

As I need to persist that datum for another call, I try to reassign it before returning the view.

public ActionResult ChangePassword()
{
    string t = (string)TempData["myVariable"];
    [..]

    TempData["myVariable"] = TempData["myVariable"];
    return View();
}

I immediately submit a POST request from the rendered page back to ChangePassword, but this time TempData["myVariable"] is null. Maybe I'm doing something stupid, but how to get the wanted result? I don't want to use a Session variable (it would persist much longer and I'd be working on ensuring manually that the variable is cleared to prevent the pollution of Session variables). I could repost it via the form (a hidden variable) but I'd prefer to keep the variable only server-side.


Solution

  • I think you're looking for TempData.Keep()