TempData 生命周期
保存到 TempData 的数据存储在会话中,并将在访问数据的第一个请求结束时自动删除。如果从未读过,它将一直保留到最后读取或会话超时。
典型用法类似于以下序列(其中每行从不同的请求调用):
//first request, save value to TempData
TempData["value"] = "someValueForNextRequest";
//second request, read value, which is marked for deletion
object value = TempData["value"];
//third request, value is not there as it was deleted at the end of the second request
TempData["value"] == null
-
使用
Peek
,你可以检索存储在 TempData 中的数据,而不会将其标记为删除,因此将来的请求仍然可以使用数据//first request, save value to TempData TempData["value"] = "someValueForNextRequest"; //second request, PEEK value so it is not deleted at the end of the request object value = TempData.Peek("value"); //third request, read value and mark it for deletion object value = TempData["value"];
-
使用
Keep
,你可以指定实际上应保留标记为删除的密钥。在这种情况下,检索数据并将其保存为删除需要 2 个方法调用://first request, save value to TempData TempData["value"] = "someValueForNextRequest"; //second request, get value marking it from deletion object value = TempData["value"]; //later on decide to keep it TempData.Keep("value"); //third request, read value and mark it for deletion object value = TempData["value"];
考虑到这一点,当你总是希望保留另一个请求的值时使用 Peek
并在保留值时使用 Keep
取决于额外的逻辑。