Asp.net-Mvc

TempData 保持()與窺視()

  • January 21, 2014

keep() 和 peek() 有什麼區別?

MSDN 說:

  • 保持():marks the specified key in the dictionary for retention.
  • 窺視():returns an object that contains the element that is associated with the specified key, without marking the key for deletion.

我真的不知道有什麼區別,他們不是都為另一個請求保留一個值嗎?

TempDataDictionary讀取 a 中的對象時,將在該請求結束時將其標記為刪除。

這意味著如果你在 TempData 上放一些東西,比如

TempData["value"] = "someValueForNextRequest";

在您訪問它的另一個請求中,該值將在那裡,但一旦您讀取它,該值將被標記為刪除:

//second request, read value and 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

和方法允許您讀取值而不將PeekKeep標記為刪除。假設我們回到將值保存到 TempData 的第一個請求。

只需Peek一次呼叫即可獲得值而無需將其標記為刪除,請參閱msdn

//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 個不同的呼叫。見msdn

//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取決於附加邏輯。

你有 2 個關於 TempData 如何在這里這里工作的好問題

希望能幫助到你!

引用自:https://stackoverflow.com/questions/21252888