2011-01-10 100 views
1

我遇到了自定義控件(從用戶控件繼承)的問題 - 我的LoadControlState未被觸發。LoadControlState未被觸發

嗯,確切地說:它被正常觸發,但是當我重寫頁面的LoadPageStateFromPersistenceMedium和SavePageStateToPersistenceMedium函數時,它不再被觸發。

是否有任何典型的原因LoadControlState沒有被激發,我應該看看?當確實被解僱時,是否有任何先決條件?

感謝

回答

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)); 
     } 
    } 
0

由於.NET 2.0,則建議把你的狀態持續的邏輯從PageStatePersister派生的自定義類。所以你可以嘗試採取這種方法。

+0

我也試過了,通過覆蓋Page的PageStatePersister屬性和返回'新的SessionPageStatePersister(this);' - 這與之前的結果相同。 – Chris 2011-01-10 21:13:19

+1

@Chris,你在自定義控件的OnInit中調用了Page.RegisterRequiresControlState?還有一件事是檢查控制ID是否發生變化(或稍後分配)。 – VinayC 2011-01-11 04:26:36

0

你從LoadPageStateFromPersistenceMedium方法實施返回什麼?這大概應該是既ViewState中和了ControlState-數據初始化的System.Web.UI.Pair的一個實例:

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

對於它的價值,這裏就是我如何重寫保存/的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()); 
    }