Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewBag/ViewData Lifecycle

I have seen many posts about when to use ViewBag/ViewData vs ViewModel but i have not been able to find an explanation of the lifecycle of the ViewBag.

For example, i have two Action methods in one Controller:

// POST: /MyModel/Edit/5 [HttpPost] public ActionResult Edit(MyModel _mymodel){} 

and

// GET: /MyModel/Edit/5 public ActionResult Edit(int id){} 

If i put some values in the ViewBag in the GET action method, to set up some Form labels, then when they user clicks 'Submit' button and the Form is posted back to the server via HTTP POST, the ViewBag values are no longer within the POST action method.

Can someone please explain (or provide reference to good article) the lifecycle of the ViewBag/ViewData ?

like image 364
JTech Avatar asked Feb 08 '12 01:02

JTech


People also ask

Does ViewBag expire?

ViewData/ViewBag - valid only for the duration of the current request. You set it in a controller action and use it in the view, then it disappears.

What is ViewBag and ViewData?

ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0. ViewData requires typecasting for complex data type and check for null values to avoid error.

What is the lifetime of TempData?

Lifespan. The lifespan of TempData is rather unusual: It lives for one request only. In order to achieve this it maintains two HashSets to manage keys as well as the data dictionary: private Dictionary<string, object> _data; private HashSet<string> _initialKeys = new HashSet<string>(StringComparer.

Which is better ViewBag or ViewData?

In theory if properly implemented, the ViewBag would ultimately outperform the use of the ViewData dictionary because the binding of the expressions (e.g. ViewBag.


1 Answers

The data you put in the ViewBag/ViewData is only available during the life-cycle of the request within which you populated it. MVC does not have post backs. If you need something to persist over more than a single request, you should use Session.

Here is a decent article about the differences between ViewData, ViewBag, and TempData: http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications

like image 99
Zach Green Avatar answered Oct 10 '22 07:10

Zach Green