我正在尝试存储一个Dictionary<string, string>
在我为 ASP.NET 2.0 开发的自定义控件的 ViewState 中:
private Dictionary<String, String> Items
{
get
{
object d = ViewState["Items"];
return (d == null ? null : (Dictionary<String, String>)d);
}
set
{
ViewState["Items"] = value;
}
}
访问它看起来像这样:
public void UpdateData
{
if (this.Items == null)
this.Items = new Dictionary<string, string>();
else
this.Items.Clear();
//Fill the collection
}
当第一次加载页面时设置它,它看起来工作正常。但在随后的回发中,返回的值始终为 null(第一个条件总是发生)。调试显示已经可以了null
在属性中的 ViewState 之外get
.
我做了一些研究并且已经found http://msdn.microsoft.com/en-us/library/ms178652%28VS.85%29.aspx该类必须实现IStateManager
可保存在 ViewState 中,并且词典 MSDN 页面 http://msdn.microsoft.com/en-us/library/xfhwa508%28v=VS.80%29.aspx似乎表明Dictionary<TKey, TValue>
才不是。但我之前在 ViewState 中存储字典没有问题。这里发生了什么?我之前的经历是侥幸吗?
更新:我尝试向该属性添加一些测试代码:ViewState["ItemTest"] = "foo";
in the set
and string test = (string)ViewState["ItemTest"];
in the get
。像Dictionary
,结果为空。所以这似乎不是问题Dictionary
可序列化。另外,为了澄清,UpdateData
是从我的RenderControl
覆盖,发生在Page_Load
在包含该控件的页面中。
您可以将字典存储在 ViewState 中,但您尝试在页面生命周期中执行此操作为时已晚。就像ViewState加载后一样Init
,ViewState被保存before控件被渲染。将你的逻辑移出RenderControl
并进入生命周期早期的另一个方法或事件处理程序,例如PreRender
.
protected override void OnPreRender(EventArgs e)
{
if (this.Items == null)
{
this.Items = new Dictionary<string, string>();
}
base.OnPreRender(e);
}
您将注意到,只要 ViewState 未在控件或其父级上禁用,该对象在后续回发中就不再为 null。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)