asp.net-mvc RedirectToAction 后 ViewBag 为 NULL(+ ViewBag 重新初始化)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10109447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ViewBag is NULL after RedirectToAction (+ reinitialization of ViewBag)
提问by drunkcamel
I have RedirectToAction as a return value in a controller and in my view I use ViewBag. While it's a well-known problem that ViewBag becomes empty after a RedirectToAction. I have a problem when I reinitialize ViewBag values in my overloaded controller in the OnActionExecuting method. ViewBag is empty again. But the problem is that on my local PC (win7) it's working okay but on the web-hosting server (win 2008) it crashes. So can some one help saying what can cause that? Maybe it's a setting or something?
我有 RedirectToAction 作为控制器中的返回值,在我看来我使用 ViewBag。虽然在 RedirectToAction 之后 ViewBag 变空是一个众所周知的问题。当我在 OnActionExecuting 方法的重载控制器中重新初始化 ViewBag 值时遇到问题。ViewBag 又是空的。但问题是在我的本地 PC (win7) 上它工作正常,但在网络托管服务器 (win 2008) 上它崩溃了。那么有人可以帮忙说一下是什么原因造成的吗?也许这是一个设置或什么?
采纳答案by drunkcamel
There was an exception deep inside data layer which was incorrectly captured and thereby prevented from propagation but caused ViewBag vanishing.
数据层深处有一个异常,它被错误地捕获,从而阻止传播,但导致 ViewBag 消失。
So be careful with exceptions catching.
所以要小心捕捉异常。
回答by Erik A. Brandstadmoen
The ViewBag and ViewData only survives the current request. TempData is the thing to use when you use redirects (and only then): http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applicationsstates this clearly:
ViewBag 和 ViewData 只在当前请求中存活。TempData 是您使用重定向时要使用的东西(只有那时):http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications states这清楚地:
[...] the TempData object works well in one basic scenario:
- Passing data between the current and next HTTP requests
[...] TempData 对象在一种基本情况下运行良好:
- 在当前和下一个 HTTP 请求之间传递数据

