为什么我的UserControl的ViewState已部分保存?

时间:2017-03-02 16:54:40

标签: asp.net viewstate

我有一个充分利用this.ViewState["Key"] = SomeValue的用户控件。其中大部分是从我的Page_Init()加载的:

protected void Page_Init(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
         ViewState["Blahblah"] = LoadSomeValue();
    }
}

其余的设定在不同的点。

但出于某种原因,它在随后的回发中无法使用。我重写了SaveViewState()来检查,并且只保存其中三个!

protected override object SaveViewState()
{
    List<object> viewStateObjectsBefore = ViewState.OfType<object>().ToList();

    object ret = base.SaveViewState();

    List<object> viewStateObjectsAfter = ViewState.OfType<object>().ToList();
    GC.KeepAlive(viewStateObjectsBefore);
    GC.KeepAlive(viewStateObjectsAfter);
    GC.KeepAlive(ret);
    return ret;
}

viewStateObjectsBeforeviewStateObjectsAfter都包含10个键/值对,但ret只包含3个!

已添加:将初始化移至Page_Load()并非易于使用,因为初始化必须在父Page_Load()执行之前完成。

1 个答案:

答案 0 :(得分:0)

在我的Page_Init()末尾添加对SetDirty()的调用解决了这个问题:

protected void Page_Init(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        ViewState["Blahblah"] = LoadSomeValue();

        //Looks like the ViewState is not yet "tracking" changes before Page_Load.
        //The items have to be marked as "dirty" manually so they'll be included by SaveViewState().
        ViewState.SetDirty(true);
    }
}