2010-09-10 41 views
9

我不得不對一些用戶控件在一些頁面中使用進行一些更改。用戶控件包含一些JQuery來處理分頁任務(顯示3個月的數據並一次隱藏9個)。加載控件時,它將自動顯示當前季度並在$(document).ready()中執行此代碼。異步回發不會導致document.ready被執行

我遇到的問題是在使用用戶控件的其中一個頁面中,控件在頁面加載時不可見。異步回發用於更改可見性,但不會執行ready()。

我發現了一個代碼段,允許託管頁面攔截部分回發的EndResponse,但我仍然無法在usercontrol內執行該函數。

有沒有人有任何建議?

乾杯

戴夫

+0

您正在使用的UpdatePanel? – 2010-09-10 11:10:53

+0

是的主頁面包含許多更新面板 - 包含此用戶控件的面板也包含4個或5個其他面板。 – Dave 2010-09-10 11:14:37

+4

請參閱http://stackoverflow.com/questions/1152946/how-to-have-a-javascript-callback-executed-after-an-update-panel-postback/1153002#1153002 – 2011-03-30 11:40:44

回答

11

像我一樣,你會恨規定微軟的答案。 「規定的」答案是使用PageRequestManager來設置請求處理程序。這個請求處理程序(然後)在每個部分回發完成後執行。

請求處理程序實例:

<script id="events" type="text/javascript"> 

    jQuery(document).ready(function() { 

     // Your normal code goes here 
     setupSomething(); 
     initializeSomethingElse(); 

     // Setup your partial-postback event handler. 
     // This is used to rewire all events since all are 'lost' after partial-postback. 
     Sys.WebForms.PageRequestManager.getInstance().add_endRequest(requestHandler); 
    }); 

    ///<summary>partial postback event handler. Executed after the partial postback is completed. Clears modal popup textboxes</summary> 
    ///<param name="sender"></param> 
    ///<param name="args">http://www.asp.net/ajax/documentation/live/ClientReference/Sys.WebForms/EndRequestEventArgsClass/default.aspx</param> 
    function requestHandler(sender, args) { 

     if (args.get_error() == undefined) { 

      // Your normal code goes here 
      setupSomething(); 
      initializeSomethingElse(); 
     } 
     else 
      alert(args.get_error()); // Do something 
    } 
</script> 

這給我們帶來了簡單的答案:
爲什麼不從你的代碼隱藏明確初始化您的用戶控制和保持這種內初始化JavaScript的您的用戶控制HTML(本身)。

void YourUserControl_PreRender(object sender, EventArgs e) 
{ 
    try 
    { 

    } 
    catch (Exception ex) 
    { 

    } 
    finally 
    { 
     // Do this 
     ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "registerInitializer", buildInitializer(), true); 
    } 
} 

一旦呈現時,「buildInitializer」從邏輯上說,「如果客戶端上存在此功能...調用它。」而且......每次都有效。

private string buildInitializer() 
{ 
    StringBuilder javascript = new StringBuilder(); 

    javascript.Append("if (window.initializeMyControl) {"); 
    javascript.Append("if(typeof window.initializeMyControl == 'function') { initializeMyControl(); }"); 
    javascript.Append("}"); 

    return javascript.ToString(); 
} 

現在你的用戶控件初始化可以住在用戶控件應在何處:

<script type="text/javascript"> 
    function initializeMyControl() { 

     // Your normal code goes here 
     setupSomething(); 
     initializeSomethingElse(); 
    } 
</script> 
+0

+1非常有幫助的答案,謝謝。在我實現你的解決方案後,我看到了這個問題中的流行評論,並用更少的代碼解決了我的問題:http://stackoverflow.com/questions/1152946/how-to-have-a-javascript-callback-executed-after-一個更新面板一回發/ 1153002#1153002 – daniloquio 2012-03-22 18:39:42