c# - ASP.NET StateBag 和自定义控件

标签 c# asp.net viewstate custom-server-controls

假设出于某种原因我想创建一个派生自 Control 而不是 WebControl 的自定义控件。我们还假设我需要处理属性(即实现 IAttributeAccessor),并且我想像 WebControl 一样通过使用 AttributeCollection 来实现。

WebControl 像这样实现 Attributes 属性:


public AttributeCollection Attributes
{
    get
    {
        if (this.attrColl == null)
        {
            if (this.attrState == null)
            {
                this.attrState = new StateBag(true);
                if (base.IsTrackingViewState])
                {
                    this.attrState.TrackViewState();
                }
            }
            this.attrColl = new AttributeCollection(this.attrState);
        }
        return this.attrColl;
    }
}

注意以下几点:

  1. 如果不提供 StateBag,则无法创建 AttributeCollection。
  2. 我们必须创建一个新的 StateBag。重用控件的 StateBag 是不明智的,因为属性的名称可能作为控件存储的值。
  3. 我们不能在 StateBag 上调用 TrackViewState,因为这是一个内部方法。
  4. StateBag 是一个密封类。

据我了解,如果我想使用 AttributeCollection,我必须使用一个新的 StateBag,它永远(不诉诸反射等技巧)实际上无法正确管理状态。

我错过了什么吗?

最佳答案

要在自定义 StateBag 上调用 TrackViewState,您必须将其转换为它的接口(interface)。

StateBag mybag = new StateBag();
(mybag as IStateManager).TrackViewState();

我猜这个设计决定是为了向消费者隐藏 ViewState 的实现。有一些关于在 documentation page for IStateManager 上实现自定义状态跟踪的信息。 .

关于c# - ASP.NET StateBag 和自定义控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1160442/

相关文章:

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

c# - 如果落后则跳过帧渲染

c# - Xamarin - 删除 Android 中的 SearchBar 下划线

c# - 为标签系统设计数据库的最有效方法

asp.net - 使用 VS 2008 对托管主机进行压力测试

c# - 使用 ViewState 和 ViewStateMode ="Disabled"EnableViewState ="true"

c# - 设置 RunWorkerCompleted 值

c# - 如何正确绑定(bind) WPF TreeView 控件并有效地显示数据的层次结构?

c# - 如何处理单击按钮时使用 Javascript 弹出的 Yes No 对话框

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