惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cloudbric
Cloudbric
E
Exploit-DB.com RSS Feed
SecWiki News
SecWiki News
Forbes - Security
Forbes - Security
N
News | PayPal Newsroom
S
Security @ Cisco Blogs
Schneier on Security
Schneier on Security
V
V2EX - 技术
S
Secure Thoughts
W
WeLiveSecurity
Google DeepMind News
Google DeepMind News
C
CERT Recently Published Vulnerability Notes
NISL@THU
NISL@THU
S
Securelist
S
Security Archives - TechRepublic
Know Your Adversary
Know Your Adversary
V
Vulnerabilities – Threatpost
Security Latest
Security Latest
Recent Commits to openclaw:main
Recent Commits to openclaw:main
G
GRAHAM CLULEY
H
Hacker News: Front Page
Microsoft Azure Blog
Microsoft Azure Blog
I
Intezer
Google Online Security Blog
Google Online Security Blog
美团技术团队
阮一峰的网络日志
阮一峰的网络日志
T
The Exploit Database - CXSecurity.com
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Webroot Blog
Webroot Blog
Jina AI
Jina AI
Engineering at Meta
Engineering at Meta
P
Proofpoint News Feed
The Cloudflare Blog
I
InfoQ
L
LangChain Blog
U
Unit 42
P
Proofpoint News Feed
S
Schneier on Security
S
Security Affairs
Y
Y Combinator Blog
T
Tenable Blog
N
News and Events Feed by Topic
MyScale Blog
MyScale Blog
量子位
Google DeepMind News
Google DeepMind News
Cyberwarzone
Cyberwarzone
博客园 - 聂微东
D
Darknet – Hacking Tools, Hacker News & Cyber Security
GbyAI
GbyAI
AWS News Blog
AWS News Blog

博客园 - 简约旋律

如何做一名优秀的部门经理 Repeater/DataList分页方法 char与varchar的区别 堂堂正正做人 认认真真做事 笨鸟 节约时间 ASP.NET中的FILE对象总结 当梦想照进现实 (C#) C#中的@符号 数据库事务 读写删文件代码 什么是SQL注入及SQL注入工具 void的使用 导航树扩展 按F5运行时出现目录清单 - 简约旋律 经典JS收藏 GET POST的使用 关于request的一个问题 一些代码
viewstate 的工作原理
简约旋律 · 2007-11-23 · via 博客园 - 简约旋律


  ViewState是一种机制,ASP.NET 使用这种机制来跟踪服务器控件状态值,否则这些值将不作为 HTTP 窗体的一部分而回传。例如,由 Label 控件显示的文本默认情况下就保存在 ViewState 中。作为开发人员,您可以绑定数据,或在首次加载该页面时仅对 Label 编程设置一次,在后续的回传中,该标签文本将自动从 ViewState 中重新填充。因此,除了可以减少繁琐的工作和代码外,ViewState 通常还可以减少数据库的往返次数。
  ViewState 确实没有什么神秘之处,它是由 ASP.NET 页面框架管理的一个隐藏的窗体字段。当 ASP.NET 执行某个页面时,该页面上的 ViewState 值和所有控件将被收集并格式化成一个编码字符串,然后被分配给隐藏窗体字段的值属性(即 <input type=hidden>)。由于隐藏窗体字段是发送到客户端的页面的一部分,所以 ViewState 值被临时存储在客户端的浏览器中。如果客户端选择将该页面回传给服务器,则 ViewState 字符串也将被回传。在上面的图 2 中可以看到 ViewState 窗体字段及其回传的值。
  回传后,ASP.NET 页面框架将解析 ViewState 字符串,并为该页面和各个控件填充 ViewState 属性。然后,控件再使用 ViewState 数据将自己重新恢复为以前的状态。

关于 ViewState 还有三个值得注意的小问题。
  如果要使用 ViewState,则在 ASPX 页面中必须有一个服务器端窗体标记 (<form runat=server>)。窗体字段是必需的,这样包含 ViewState 信息的隐藏字段才能回传给服务器。而且,该窗体还必须是服务器端的窗体,这样在服务器上执行该页面时,ASP.NET 页面框架才能添加隐藏的字段。
页面本身将 20 字节左右的信息保存在 ViewState 中,用于在回传时将 PostBack 数据和 ViewState 值分发给正确的控件。因此,即使该页面或应用程序禁用了 ViewState,仍可以在 ViewState 中看到少量的剩余字节。
在页面不回传的情况下,可以通过省略服务器端的 <form> 标记来去除页面中的 ViewState。

充分利用 ViewState
  ViewState 为跨回传跟踪控件的状态提供了一条神奇的途径,因为它不使用服务器资源、不会超时,并且适用于任何浏览器。如果您要编写控件,那么肯定需要了解如何在控件中维护状态(英文)。
  开发人员在编写页面时同样可以按照几乎相同的方式来利用 ViewState,只是有时页面会包含不由控件存储的 UI 状态值。您可以跟踪 ViewState 中的值,使用的编程语法与会话和高速缓存的语法类似:
  请看下面的示例:要在 Web 页上显示一个项目列表,而每个用户需要不同的列表排序。项目列表是静态的,因此可以将这些页面绑定到相同的缓存数据集,而排序顺序只是用户特定的 UI 状态的一小部分。ViewState 非常适合于存储这种类型的值。代码如下:

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<HTML>
    <HEAD>
        <title>用于页面 UI 状态值的 ViewState</title>
    </HEAD>
    <body>
        <form runat="server">
            <H3>
                在 ViewState 中存储非控件状态
            </H3>
            <P>
                此示例将一列静态数据的当前排序顺序存储在 ViewState 中。<br>
                单击列标题中的链接,可按该字段排序数据。<br>
                再次单击该链接,将按相反顺序排序。
                <br><br><br>
                <asp:datagrid id="DataGrid1" runat="server" OnSortCommand="SortGrid"
                BorderStyle="None" BorderWidth="1px" BorderColor="#CCCCCC"
                BackColor="White" CellPadding="5" AllowSorting="True">
                    <HeaderStyle Font-Bold="True" ForeColor="White" BackColor="#006699">
                    </HeaderStyle>
                </asp:datagrid>
            </P>
        </form>
    </body>
</HTML>
<script runat="server">

    // 在 ViewState 中跟踪 SortField 属性
    string SortField {

        get {
            object o = ViewState["SortField"];
            if (o == null) {
                return String.Empty;
            }
            return (string)o;
        }

        set {
            if (value == SortField) {
                // 与当前排序文件相同,切换排序方向
                SortAscending = !SortAscending;
            }
            ViewState["SortField"] = value;
        }
    }

    // 在 ViewState 中跟踪 SortAscending 属性
    bool SortAscending {

        get {
            object o = ViewState["SortAscending"];
            if (o == null) {
                return true;
            }
            return (bool)o;
        }

        set {
            ViewState["SortAscending"] = value;
        }
    }

    void Page_Load(object sender, EventArgs e) {

        if (!Page.IsPostBack) {
            BindGrid();
        }
    }

    void BindGrid() {

        // 获取数据
        DataSet ds = new DataSet();
        ds.ReadXml(Server.MapPath("TestData.xml"));
       
        DataView dv = new DataView(ds.Tables[0]);

        // 应用排序过滤器和方向
        dv.Sort = SortField;
        if (!SortAscending) {
            dv.Sort += " DESC";
        }

        // 绑定网格
        DataGrid1.DataSource = dv;
        DataGrid1.DataBind();
   }

   void SortGrid(object sender, DataGridSortCommandEventArgs e) {

        DataGrid1.CurrentPageIndex = 0;
        SortField = e.SortExpression;
        BindGrid();
    }

</script>

下面是上述代码段中引用的 testdata.xml 的代码:

<?xml version="1.0" standalone="yes"?>
<NewDataSet>
  <Table>
    <pub_id>0736</pub_id>
    <pub_name>New Moon Books</pub_name>
    <city>Boston</city>
    <state>MA</state>
    <country>USA</country>
  </Table>
  <Table>
    <pub_id>0877</pub_id>
    <pub_name>Binnet &amp; Hardley</pub_name>
    <city>Washington</city>
    <state>DC</state>
    <country>USA</country>
  </Table>
  <Table>
    <pub_id>1389</pub_id>
    <pub_name>Algodata Infosystems</pub_name>
    <city>Berkeley</city>
    <state>CA</state>
    <country>USA</country>
  </Table>
  <Table>
    <pub_id>1622</pub_id>
    <pub_name>Five Lakes Publishing</pub_name>
    <city>Chicago</city>
    <state>IL</state>
    <country>USA</country>
  </Table>
  <Table>
    <pub_id>1756</pub_id>
    <pub_name>Ramona Publishers</pub_name>
    <city>Dallas</city>
    <state>TX</state>
    <country>USA</country>
  </Table>
  <Table>
    <pub_id>9901</pub_id>
    <pub_name>GGG&amp;G</pub_name>
    <city>Muenchen</city>
    <country>Germany</country>
  </Table>
  <Table>
    <pub_id>9952</pub_id>
    <pub_name>Scootney Books</pub_name>
    <city>New York</city>
    <state>NY</state>
    <country>USA</country>
  </Table>
  <Table>
    <pub_id>9999</pub_id>
    <pub_name>Lucerne Publishing</pub_name>
    <city>Paris</city>
    <country>France</country>
  </Table>
</NewDataSet>