TempData keep() 与 peek() [英] TempData keep() vs peek()

查看:28
本文介绍了TempData keep() 与 peek()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

keep() 和 peek() 有什么区别?

What is the difference between keep() and peek()?

MSDN 说:

  • keep():在字典中标记指定键以供保留.
  • peek(): 返回一个包含元素的对象与指定的键相关联,不标记键删除.

我真的不明白有什么区别,他们不是都为另一个请求保留了一个值吗?

I can't get really what the difference is, don't they both keep a value for another request?

推荐答案

TempDataDictionary 中的对象被读取时,它会在请求结束时被标记为删除.

When an object in a TempDataDictionary is read, it will be marked for deletion at the end of that request.

这意味着如果你在 TempData 上放一些东西

That means if you put something on TempData like

TempData["value"] = "someValueForNextRequest";

如果您访问它的另一个请求,该值将在那里,但一旦您阅读它,该值将被标记为删除:

And on another request you access it, the value will be there but as soon as you read it, the value will be marked for deletion:

//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 的请求.

The Peek and Keep methods allow you to read the value without marking it for deletion. Say we get back to the first request where the value was saved to TempData.

使用 Peek,您只需一次调用即可获得值,而无需将其标记为删除,请参阅 msdn:

With Peek you get the value without marking it for deletion with a single call, see 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

With Keep you specify a key that was marked for deletion that you want to keep. Retrieving the object and later on saving it from deletion are 2 different calls. See 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 取决于附加逻辑.

You can use Peek when you always want to retain the value for another request. Use Keep when retaining the value depends on additional logic.

您有 2 个关于 TempData 如何工作的好问题这里这里

You have 2 good questions about how TempData works here and here

希望有帮助!

这篇关于TempData keep() 与 peek()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆