TempData持久性

时间:2017-07-14 06:50:40

标签: asp.net-mvc tempdata

我最近一直与TempData合作,面对一个令人困惑的案例:

假设在以下操作中创建了TempData

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

预计将在以下Action中使用:

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

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

谢谢大家。

2 个答案:

答案 0 :(得分:3)

在这里,您可以查看Keep and Peek Temp数据以获取下一个请求:

如果您不读取Temp Data,那么它将可用于下一个后续请求

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

干杯!!

答案 1 :(得分:1)

TempData["myTempData"]

1)TempData持久性仅针对行动,假设 action1 调用您已将数据存储到 TempData [" myTempData"] 然后您需要 action2 中的访问数据将保持不变。

2)如果你想将数据存储在 TempData [" myTempData"] 中,那么在每一个动作上首先分配 TempData [&#34]的值; myTempData"] TempData [" myTempData"] 然后在每个操作中使用它,直到你强行删除它为止。

希望查询能够解决。