LoadControlState没有被触发

时间:2011-01-10 05:35:24

标签: c# asp.net user-controls viewstate

我遇到自定义控件(继承自用户控件)的问题 - 我的LoadControlState没有被触发。

嗯,确切地说:它被正常触发,但当我覆盖页面的LoadPageStateFromPersistenceMedium和SavePageStateToPersistenceMedium函数时,它不再被触发。

我应该调查一下LoadControlState没有被解雇的典型原因吗?什么时候 被解雇了?

由于

4 个答案:

答案 0 :(得分:1)

对于它的价值,这是我如何重写Save / LoadPageStateFromPersistenceMedium函数。基本上,它将视图状态存储在用户会话中,以使回发更快:

    // Inspired by: http://aspalliance.com/72
    const string ViewStateFieldName = "__VIEWSTATEKEY";
    const string ViewStateKeyPrefix = "ViewState_";
    const string RecentViewStateQueue = "ViewStateQueue";
    const int RecentViewStateQueueMaxLength = 5;

    protected override object LoadPageStateFromPersistenceMedium()
    {
        // The cache key for this viewstate is stored in a hidden field, so grab it
        string viewStateKey = Request.Form[ViewStateFieldName] as string;
        if (viewStateKey == null) return null;

        // Grab the viewstate data using the key to look it up
        return Session[viewStateKey];
    }

    protected override void SavePageStateToPersistenceMedium(object viewState)
    {
        // Give this viewstate a random key
        string viewStateKey = ViewStateKeyPrefix + Guid.NewGuid().ToString();

        // Store the viewstate
        Session[viewStateKey] = viewState;

        // Store the viewstate's key in a hidden field, so on postback we can grab it from the cache
        ClientScript.RegisterHiddenField(ViewStateFieldName, viewStateKey);

        // Some tidying up: keep track of the X most recent viewstates for this user, and remove old ones
        var recent = Session[RecentViewStateQueue] as Queue<string>;
        if (recent == null) Session[RecentViewStateQueue] = recent = new Queue<string>();
        recent.Enqueue(viewStateKey); // Add this new one so it'll get removed later
        while (recent.Count > RecentViewStateQueueMaxLength) // If we've got lots in the queue, remove the old ones
            Session.Remove(recent.Dequeue());
    }

答案 1 :(得分:0)

从.NET 2.0开始,建议将状态持久逻辑放在从PageStatePersister派生的自定义类中。所以你可以尝试采用这种方法。

答案 2 :(得分:0)

您从LoadPageStateFromPersistenceMedium方法实施中返回了什么?它应该是使用ViewState和ControlState数据初始化的System.Web.UI.Pair的实例:

return new Pair([Restored ControlState], [Restored ViewState]);

答案 3 :(得分:0)

以下代码修复了它:

    PageStatePersister pageStatePersister;
    protected override PageStatePersister PageStatePersister
    {
        get
        {
            // Unlike as exemplified in the MSDN docs, we cannot simply return a new PageStatePersister
            // every call to this property, as it causes problems
            return pageStatePersister ?? (pageStatePersister = new SessionPageStatePersister(this));
        }
    }