【问题标题】:TempData persistence临时数据持久化
【发布时间】:2017-07-14 15:16:15
【问题描述】:

我最近一直在与TempData 合作并面临一个令人困惑的案例:

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

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

预计将用于以下操作:

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

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

谢谢大家。

【问题讨论】:

  • 你试过了吗?据我了解,这使用 session 来存储数据并在读取数据时被清除,除非使用 .Peek 读取
  • 无论你要调用哪个action method,它都会在后续请求(重定向)中可用。
  • @Slicksim 我也这么认为,但不太确定:D

标签: asp.net-mvc tempdata


【解决方案1】:

您可以在此处获取 Keep 和 Peek Temp Data For next 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();

干杯!!

【讨论】:

  • 所以就像请求 1 我创建了 TempData,请求 2 3 4 我不阅读它而是调用其他操作,然后在请求 5 上 TempData 仍然存在?
【解决方案2】:
TempData["myTempData"]

1) TempData 仅在操作到操作时持久化,假设 action1 调用您已将数据存储到 TempData["myTempData"] 那么您需要访问数据在 action2 将持续存在。

2) 如果您想将数据存储在 TempData["myTempData"] 中,那么在每个操作中首先分配 TempData["myTempData"] 的值TempData["myTempData"] 然后在每个操作中使用它,直到您将其强制删除。

希望查询能得到解决。

【讨论】:

  • 谢谢 :D 我会考虑使用你的解决方案 :D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多