asp.net-mvctempdata

TempData persistence


I've been working with TempData lately and facing a confusing case:

Supposing that the TempData is created in the following Action:

public ActionResult MyAction1()
{
  //...
  myTempData = TempData["myTempData"];
  //..
}

and is expected to be use in the following Action:

public ActionResult MyAction2()
{
  //...
  TempData["myTempData"] = myTempData;
  //..
}

I understand that if I call MyAction2 on the next request, the TempData value will be deleted. But if I call other action, not MyAction2, on the next request, will TempData be deleted? If it will be, is there any trick to make sure it exist until the end of the session?

Thanks all.


Solution

  • Here you go for Keep and Peek Temp Data For next Request :

    If you won't read Temp Data then it will be available for next subsequent request

    So let’s discuss these four conditions in more detail

    “Tempdata helps to preserve values for a single request”.

    The other half-truth which developers do not know is or I will say which confuses developer is:

    “TempData CAN ALSO preserve values for the next request depending on 4 conditions”..

    1. Not Read
    2. Normal Read
    3. Read and Keep
    4. Peek and Read

    Condition 1 (Not read): If you set a “TempData” inside your action and if you do not read it in your view, then “TempData” will be persisted for the next request.

    Condition 2 (Normal Read): If you read the “TempData” normally like the below code, it will not persist for the next request.

       stringstr = TempData["MyData"];
    

    Even if you are displaying, it’s a normal read like the code below:

       @TempData["MyData"];
    

    Condition 3 (Read and Keep): If you read the “TempData” and call the “Keep” method, it will be persisted.

       @TempData["MyData"];
       TempData.Keep("MyData");
    

    Condition 4 ( Peek and Read): If you read “TempData” by using the “Peek” method, it will persist for the next request.

       stringstr = TempData.Peek("Td").ToString();