临时数据持久化

TempData persistence

我最近一直在与 TempData 合作,遇到一个令人困惑的案例:

假设 TempData 是在以下操作中创建的:

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

预计将在以下操作中使用:

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

我知道如果我在下一次请求时调用 MyAction2TempData 值将被删除。但是,如果我在下一个请求中调用其他操作,而不是 MyAction2,是否会删除 TempData?如果会,是否有任何技巧可以确保它一直存在到会话结束?

谢谢大家

在这里,您可以为下一个请求保留和查看临时数据:

如果您不读取临时数据,那么它将可用于下一个后续请求

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();

干杯!!

TempData["myTempData"]

1) TempData 持久性仅在操作之间进行,假设 action1 调用您已将数据存储到 TempData["myTempData"] 那么您需要 action2 中的访问数据,这将明确保留。

2) 如果要将数据存储在 TempData["myTempData"] 中,则在每个操作上首先分配 TempData 的值["myTempData"]TempData["myTempData"] 然后在每个操作中使用它,直到你将它强行删除。

希望问题得到解决。