ASP.NET MVC 浏览器刷新会使 TempData 失效吗?
如果我重定向到一个新页面并传递 TempData 来初始化该页面,则该页面工作正常,但是如果用户按下浏览器中的刷新按钮,则 TempData 将不再可用。 鉴于此,是否存在可以可靠使用 TempData 的情况?
或者有什么方法可以消除或减轻用户刷新的问题?
If I redirect to a new page passing TempData to initialise the page it works fine, however if the user presses the refresh button in their browser the TempData is no-longer available.
Given this, is there any situation where TempData could be used reliably?
Or any way to remove or mitigate the problem of users refreshing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
写入,然后它也会在刷新情况下保留该数据。
您应该在控制器中
You should write
in your controller, then it will keep that data in refresh situations too.
在 MVC 1 中,是的,存储密钥后的下一个请求后,临时数据会丢失。
然而,对于 MVC 2,临时数据在第一次尝试访问后就会丢失。
您始终可以使用 Session(TempData 无论如何都使用它)来解决您遇到的临时数据丢失问题。
来自 MVC 2 Beta 发行说明:
您还可以直接查看 MVC 2 源代码以查看这些更改:
MVC 1:
MVC 2:
In MVC 1, yes, temp data is lost after the next request after you store a key.
With MVC 2 however, the temp data is lost after the first attempt to access it.
You can always use Session, which TempData uses anyway, to solve the temp data loss issue your having.
From the MVC 2 Beta Release Notes:
You can also look directly in the MVC 2 source to see these changes:
MVC 1:
MVC 2:
针对 MVC1 中给定情况的解决方法是在第二个控制器中重新分配 TempData。当然,它会将数据在系统中保留一段时间。但它解决了刷新问题。
A workaround for the the given situation in MVC1 would be to re-assign the TempData in the second controller as well. Of course it persists the data in the system for a bit more time. but it fixes the refresh issue.
Tempdata 跨重定向使用,因此如果您刷新页面,则意味着您正在向服务器发出单独的请求,这就是数据丢失的原因。要保留此数据,请在要重定向到的操作中调用 Tempdata.Keep("KeyofTempdata") 方法。如果要删除数据,请使用 Tempdata.Remove("KeyofTempdata")。
Tempdata is used across redirects so if you are refreshing the page that means you are making a separate request to the server so that is why your data gets lost. To persist this data call Tempdata.Keep("KeyofTempdata") method in the action to which you are redirecting. If you want to remove data use Tempdata.Remove("KeyofTempdata").
唯一可以解决您的问题的功能是
Cache
和Session
。当视图生成时,
ViewData
本质上就“消失”了。如果您可以提供有关您要完成的任务的更多详细信息,也许可以给出另一种解决方案,但是,对您来说最好的选择似乎是使用
Session
或Cache
。The only features that can solve your issue is
Cache
andSession
.ViewData
essentially 'dies' out when the view is generated.If you can provide more details on what you're trying to accomplish, maybe another solution can be given, however, it seems the best option for you is to use
Session
orCache
.TempData 专门用于存储一页加载/操作/重定向的数据。如果您需要刷新后保留数据,则应将其放置在 ViewData 集合中,只要为刷新请求提供服务的操作与最初请求的操作相同(即,在重定向之前未添加 ViewData 值) 。
TempData exists specifically to store the data for just one page load/action/redirect. If you need the data to persist after a refresh you should place it in the ViewData collection so long as the action that is serving the refresh request is the same one as was initially requested (i.e. the ViewData value was not added prior to a Redirect).