asp.net - 我如何决定在viewstate中存储什么?

标签 asp.net viewstate

我一直在写一堆通用的ASP.NET控件,我似乎无法确定的一件事是何时将值存储在viewstate中,以及何时假定可以不这样做。

一方面,将控件的整个状态存储在viewstate中是有意义的,包括如下属性:

  • 用户输入的文本框值(或任何表单数据)
  • 配置选项,例如高度或页面大小
  • 甚至是控件的组成方式-例如存储构建网格 View 所依据的所有数据,或者存储网格本身。

  • 忽略性能,您可以在 View 状态中使用的越多越好,因为这意味着控件在回发之间的行为将完全相同,并且永远不会“偶然地”还原值或“忘记”被禁用的值。但是viewstate不是免费的。存储所有内容意味着控件现在将同时输出HTML及其所有内部属性以创建该HTML,这几乎总是输出的两倍以上。

    我的问题不是绩效,而是战略。 我决定根据什么标准将属性置于 View 状态? 我正在按照以下思路考虑:

    If the user can't change a property, then the server will always set it explicitly, so it's OK to leave it out of viewstate. Even for something like color=red, the user doesn't set this property directly; they will click a button elsewhere which indirectly sets this property. That button or its owner should keep the state, not the control that renders the color red.



    此逻辑意味着应该进入viewstate的唯一属性是:
  • <input>这样的表单元素(使用Request.Form[c.UniqueID]仍可以避免)
  • 用户可以直接在控件上进行交互式控制的属性。

  • 这种逻辑有意义吗?它似乎很虚弱,我想听听专家的更多信息。

    最佳答案

    使用ViewState来执行控件不需要的操作。

    即使禁用了ViewState,也可以使用ControlState来使控件正常工作所必需的东西。

    首次请求页面时,初始值和控件层次结构(甚至是html-controls)都被编译到ASP.NET临时文件中。因此,无需更改它们就无需将它们存储在任何位置(甚至ViewState也不会保存它们)。

    控件仅将ViewState中存储的属性存储在页面的生命周期中(自TrackViewState开始)。状态被更改的控件为“脏”。例如,如果您在page_load中更改TextBox1.Text,则 ViewState.IsItemDirty("TextBox1.Text") 将返回true。这些值将存储在ViewState中。

    herehere。 (我真的建议您阅读这两篇文章)

    Control State vs. View State Example

    关于asp.net - 我如何决定在viewstate中存储什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12217748/

    相关文章:

    asp.net - Paypal 多参数返回,cancel_return urls

    c# - 在 Linq where 子句中将 int 转换为字符串

    asp.net - 为什么 ASP.NET ViewState 保留为 asp :dropdownlist but not an asp:table?

    c# - 动态文本框在asp.net中添加按钮单击和数据 session

    asp.net - 如何创建通用 StateManagedCollection?

    asp.net - 在 IIS 上运行的 ASP.Net 应用程序中调用 Thread.Run

    c# - .NET 和 MySQL 错误 - 调用 SSPI 失败 ... "message received was unexpected or badly formatted"和 "buffers supplied to a function was too small"

    asp.net - 如何在 Controller 中获取路由 url?

    asp.net - ViewState 不需要保留控件值,那么它有什么作用呢?

    asp.net - 我有一个关于 ViewState 的问题