16

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.

Donato Szilagyi
  • 4,279
  • 4
  • 36
  • 53
dotnetN00b
  • 5,021
  • 13
  • 62
  • 95

3 Answers3

9

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.

RPM1984
  • 72,246
  • 58
  • 225
  • 350
  • 1
    ViewBag has it's place, for example using DropDownList and passing selectlist. Examine MVC Scaffolded CRUD - it uses the ViewBag. Your statement is too strong. Perhaps, View Models are preferred over ViewBag when appropriate. see http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications – RickAndMSFT Mar 12 '12 at 21:47
  • 1
    @Rick.Anderson-at-Microsoft.com - agreed that my statement may be strong, but not in the case of DropDownList. Your ViewModel can (and should) have a property for the `SelectList`, which can be bound to in your View. Absolutely no need for ViewBag there. – RPM1984 Mar 12 '12 at 22:58
  • The SelectList code is generated by the ASP.NET MVC tooling, and most folks consider that the right choice for an automatic scaffolder. – RickAndMSFT Mar 14 '12 at 02:16
  • 1
    @Rick.Anderson-at-Microsoft.com - in many ways, the scaffolding is an *example*, certainly not always **best practice**. Guess we'll have to agree to disagree. – RPM1984 Mar 14 '12 at 10:19
6

Viewstate is posted back along with the content of a form to the server and thus values in it are available on post back. A viewbag only holds the values in it until the page is served then the ViewBag is removed from memory. So you can use ViewState to hold state between calls but you can not do the same with a ViewBag.

GrantVS
  • 2,073
  • 1
  • 24
  • 27
4

the ViewBag doesn't get sent to the client ( Browser ). Its purely something to use transitioning from the controller to the View ( which is before its sent back to the client).

In MVC, If you get a postback from that page, then you wont recover your "state", like Viewstate does, the only state you have is whatever you send to the browser, and whatever you send back.

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156