简体   繁体   English

我什么时候需要使用ViewState

[英]When do I need to use ViewState

I am confused in how to use ViewState in C#, for example what is the benefit of using: 我对如何在C#中使用ViewState感到困惑,例如使用的好处是什么:

ViewState["VST"]="Value1";

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

Whereas I can use: 我可以使用:

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

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. 您的ViewState由与页面的回发保留的变量组成,因为它们被发送到客户端,客户端将它们与整个页面一起发回。

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. 然后用户看到页面并点击提交按钮,您的container字符串将不存在。

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. 但是,如果您使用ViewState,ViewState [“VST”]仍将具有该值,因为当用户提交并发回页面时它将被“刷新”。

Read more here and also understand the ASP.NET page life cycle. 在这里阅读更多内容并了解ASP.NET页面生命周期。

As per documentation: 根据文件:

View state is used automatically by the ASP.NET page framework to persist information that must be preserved between postbacks. ASP.NET页面框架自动使用视图状态来保留必须在回发之间保留的信息。 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 有关详细信息,请参阅链接: http//msdn.microsoft.com/en-us/library/bb386448(v = vs.100).aspx

如果你想在回发后保持值,那么ViewState也是最好的选择。

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. 因此,为了在页面中存储任何值,您可以将它们保存在ViewState中。 Of course you must set the EnableViewState property first to true. 当然,您必须首先将EnableViewState属性设置为true。 Additional info, if you want to store any value or state while jumping into multiple pages you can use Session instead. 其他信息,如果您想在跳转到多个页面时存储任何值或状态,则可以使用Session。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM