我在自定义控件(继承自用户控件)上遇到问题-我的LoadControlState没有被解雇。

好吧,准确地说:它会正常启动,但是当我覆盖页面的LoadPageStateFromPersistenceMedium和SavePageStateToPersistenceMedium函数时,它将不再被启动。

是否有任何典型原因导致我不应该调查LoadControlState?它何时被解雇是否有任何先决条件?

谢谢

最佳答案

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

    // 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());
    }

10-04 19:45