Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewBag is NULL after RedirectToAction (+ reinitialization of ViewBag)

Tags:

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?

like image 478
drunkcamel Avatar asked Apr 11 '12 15:04

drunkcamel


2 Answers

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-applications states this clearly:

[...] the TempData object works well in one basic scenario:

  • Passing data between the current and next HTTP requests
like image 179
Erik A. Brandstadmoen Avatar answered Nov 16 '22 14:11

Erik A. Brandstadmoen


There was an exception deep inside data layer which was incorrectly captured and thereby prevented from propagation but caused ViewBag vanishing.

So be careful with exceptions catching.

like image 40
drunkcamel Avatar answered Nov 16 '22 13:11

drunkcamel