Difference between viewbag and viewstate?

我的梦境 提交于 2019-11-30 06:49:14

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!