ASP.NET ViewState 的工作原理

标签 asp.net viewstate

我的 .aspx 页面上有一个文本框和按钮。文本框的 EnableViewState 属性设置为 false。但是,当我在文本框中输入一些文本并单击按钮时,输入的文本仍然存在于文本框中。我希望文本框为空,因为 EnableViewState 设置为 false。我错过了什么吗?

最佳答案

请查看this Code Project article更好地理解 ViewState 和回发数据。

它是这样的:

Why some controls retain values even after disabling the ViewState while others do not?

The answer is Controls which implements IPostBackEventHandler IPostBackDataHandler like Textbox, Checkbox, etc. will retain the state even after disabling the viewstate. The reason is during the Load Postback Data stage, these controls will get state information from Posted back form.

But controls like label which do not implement IPostBackEventHandler IPostBackDataHandler will not get any state information from posted back data and hence depend entirely on viewstate to maintain the state.

以下是与您的问题相关的段落。

In page life cycle, two events are associated with ViewState:

  • Load View State: This stage follows the initialization stage of page lifecycle. During this stage, ViewState information saved in the previous postback is loaded into controls. As there is no need to check and load previous data, when the page is loaded for the first time this stage will not happen. On subsequent postback of the page as there may be previous data for the controls, the page will go through this stage.

  • Save View State: This stage precedes the render stage of the page. During this stage, current state (value) of controls is serialized into 64 bit encoded string and persisted in the hidden control (__ViewState) in the page.

  • Load Postback Data stage: Though this stage has nothing to do with ViewState, it causes most of the misconception among developers. This stage only happens when the page has been posted back. ASP.NET controls which implement IPostBackEventHandler IPostBackDataHandler will update its value (state) from the appropriate postback data. The important things to note about this stage are as follows:

    1. State (value) of controls are NOT retrieved from ViewState but from posted back form.
    2. Page class will hand over the posted back data to only those controls which implement IPostBackEventHandler IPostBackDataHandler.
    3. This stage follows the Load View State stage, in other words state of controls set during the Load View State stage will be overwritten in this stage.

关于ASP.NET ViewState 的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1475806/

相关文章:

asp.net - 在 PostBack 上保留动态 UserControl

c# - 让 asp.net 在 session 中存储 View 状态而不是增加 html

c# - 在 ASP.Net ScriptMethod 中获取 session

c# - 在 .net 中使用 SmtpClient 发送邮件

asp.net - 如何优化 View 状态的类

javascript - 如何使用 javascript 访问 View 状态?

c# - Web 自定义控件数据存储位置

javascript - Bootstrap 模态提交我的表单

asp.net - 如何设置输入元素的样式

c# - 不循环更新数据表中的多行