When do I need to use ViewState

不问归期 提交于 2019-12-10 23:08:50

问题


I am confused in how to use ViewState in C#, for example what is the benefit of using:

ViewState["VST"]="Value1";

Lable1.Text= ViewState["VST"].ToString();

Whereas I can use:

string container= "Value1";
Lable1.Text= container;

回答1:


Your ViewState consists of variables that are kept with the post-backs of your page, because they are sent to the client and the client sends them back with the entire page.

Hence, if you do:

string container= "Value1";
Lable1.Text= container;

Then the users sees the page and hits the submit button, your container string will not exist.

If however you uses the ViewState, ViewState["VST"] will still have the value as it will be "refreshed" when the user submits and sends the page back.

Read more here and also understand the ASP.NET page life cycle.




回答2:


As per documentation:

View state is used automatically by the ASP.NET page framework to persist information that must be preserved between postbacks. This information includes any non-default values of controls. You can also use view state to store application data that is specific to a page.

For details see a link:http://msdn.microsoft.com/en-us/library/bb386448(v=vs.100).aspx




回答3:


If you want to persist the values after postback also than ViewState is the best option.




回答4:


Every time your application do postbacks current values of your controls are being wiped out. So in order for you to store any values WITHIN THE PAGE you can save them in ViewState. Of course you must set the EnableViewState property first to true. Additional info, if you want to store any value or state while jumping into multiple pages you can use Session instead.



来源:https://stackoverflow.com/questions/14807928/when-do-i-need-to-use-viewstate

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