Why is ViewState required when the Request object would have all the field values in it?
Whenever we submit a form, all the field values are posted to the server and are available within the Request object. Ideally, one can use the same object to read the values and perform any of the operations with it.
Then, why do we need ViewState to hold the values of the fields?
Please pardon my ignorance, I think I am missing out开发者_运维知识库 sometime pretty obvious here, but cant figure out what.
Most obvious reason the ViewState was introduced in ASP.Net was in order to allow a winform-like programming model (based on events).
When you have a server-side control (a textbox for instance), the html page sent back to the browser contains:
- the initial value of the control, encoded in the viewstate => this value can't be modified by the browser/user
- the control itself => the browser/user can modify its state
When the form is submitted back to the server, the ASP.Net underlying engine will compare the control new value with the initial value that was stored in the ViewState. If it's not the same, an OnChange event will be triggered, and you can attach to it as you would do in a winform application.
As per V4Vendetta, you can disable ViewState on your controls, but then you would need to develop manually "ASP classic style" e.g. if you needed to keep the user on the page and if a form failed validation, you would then need to set the initial values back to whatever the user last set them at, otherwise the user data would be lost.
The ASP Net controls handle this somewhat more elegantly by retaining this information in ViewState. But if you either never need to render the control again, or if you render the control data from fresh every time without needing its previous state (e.g. a paged grid), then disabling ViewState for the control will save you bandwidth.
A good explanation of ViewState here.
Viewstate is the ASP.NET state management technique introduced to maintain current page state between round-trip to the server. You can disable it if you don't want this feature, its purely based on how you implement your pages.
<%@ Page EnableViewState=”false”%>
精彩评论