Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between viewbag and viewstate?

Is there a functional difference between ViewState in Webforms and ViewBag in MVC? They seem to be the "same thing". And can be used in the same ways. I ask because MVC promotes the stateless Web and not stuffing data in the page causing bloat and slower performance. But it seems that you can do that in MVC as well. All they did, seemingly, is just give it a new name.

like image 936
dotnetN00b Avatar asked Mar 12 '12 02:03

dotnetN00b


People also ask

What's the difference between ViewData and ViewBag?

ViewData is a dictionary object while ViewBag is a dynamic property (a new C# 4.0 feature). ViewData being a dictionary object is accessible using strings as keys and also requires typecasting for complex types. On the other hand, ViewBag doesn't have typecasting and null checks.

What is difference between ViewBag ViewData and TempData?

We have three options: ViewData, ViewBag and TeampData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and it helps us to transfer the data from controller to view whereas TempData also works during the current and subsequent requests.

What is ViewBag used for?

In general, ViewBag is a way to pass data from the controller to the view. It is a type object and is a dynamic property under the controller base class. Compared to ViewData, it works similarly but is known to be a bit slower and was introduced in ASP.NET MVC 3.0 (ViewData was introduced in MVC 1.0).

Why ViewState is not used in MVC?

ASP.NET MVC does not use ViewState in the traditional sense (that of storing the values of controls in the web page). Rather, the values of the controls are posted to a controller method. Once the controller method has been called, what you do with those values is up to you.


1 Answers

ViewState in Web Forms was serializing form data into a hidden, encrypted field in the form, so data could be re-bound on the postback.

ViewBag/ViewData is a dictionary where you can "stuff" data into. For example, you might add to it in your Controller, then access it in your View. The data is dynamic which makes it difficult to work with the data. ViewBag doesn't get sent to the client, it's part of the MVC (server pipeline).

Both should be avoided.

ViewState by, well, not using it and finding workarounds. And ViewBag should be avoided by the use of ViewModels.

like image 85
RPM1984 Avatar answered Oct 31 '22 07:10

RPM1984