2011-11-11 40 views
4

我創建了一個服務器控件,其中嵌入了一些JavaScript文件。這工作正常,但是當服務器控件放在ajax UpdatePanel中時,它會在updatepanel內觸發異步回發後停止工作。從UpdatePanel異步回發後嵌入的JavaScript不起作用

這裏是我的服務器控件代碼:

protected override void OnPreRender(EventArgs e) 
{ 
    base.OnPreRender(e); 

    ClientScriptManager clientScriptManager = Page.ClientScript; 
    const string DATE_TIME_PICKER_JS = "JQueryControls.Scripts.DateTimePicker.js"; 

    clientScriptManager.RegisterClientScriptResource(typeof(DateTimePicker), DATE_TIME_PICKER_JS); 

    if (Ajax.IsControlInsideUpdatePanel(this) && Ajax.IsInAsyncPostBack(Page)) 
    { 
     Ajax.RegisterClientScriptResource(Page, typeof(DateTimePicker), DATE_TIME_PICKER_JS); 
    } 
} 

Ajax是一種class from this link。凡在異步回發執行該代碼

public static void RegisterClientScriptResource(Page page, Type type, string resourceName) { 
    object scriptManager = FindScriptManager(page); 
    if (scriptManager != null) { 
     System.Type smClass = GetScriptManagerType(scriptManager); 
     if (smClass != null) { 
      Object[] args = new Object[] { page, type, resourceName }; 
      smClass.InvokeMember("RegisterClientScriptResource", 
        System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | 
        System.Reflection.BindingFlags.InvokeMethod, 
        null, null, args); 
     } 
    } 
} 

如何得到這個一個UpdatePanel內工作任何想法?

回答

4

UpdatePanels使新元素在回發時被放置在頁面中。它不再是同一個元素,所以你的綁定不再適用。如果您使用jQuery並將事件捆綁在一起,則可以使用live API找到here。否則,對於諸如datepickers之類的事情來說,它會觸發一次,並從根本上改變項目的功能,您需要在加載新元素時觸發一些JavaScript;所有這一切需要的是捆綁一些javascript調用微軟提供的回調函數:

function BindEvents() 
{ 
    //Here your jQuery function calls go 
} 

var prm = Sys.WebForms.PageRequestManager.getInstance(); 
prm.add_endRequest(BindEvents); 

編輯:基於您的評論我會使DatePicker.js文件是這樣的:

$(document).ready(function() { 
    // Call BindDatePicker so that the DatePicker is bound on initial page request 
    BindDatePicker(); 

    // Add BindDatePicker to the PageRequestManager so that it 
    // is called after each UpdatePanel load 
    var prm = Sys.WebForms.PageRequestManager.getInstance(); 
    prm.add_endRequest(BindDatePicker); 
}); 

// We put the actual binding of the DatePicker to the input here 
// so that we can call it multiple times. Other binds that need to happen to the 
// elements inside the UpdatePanel can be put here as well. 
var BindDatePicker = function() { 
    $('.DatepickerInput').datepicker({ 
     showAnim: 'blind', 
     autoSize: true, 
     dateFormat: 'dd-mm-yy' 
    }); 
}; 
+0

謝謝你的反饋,但我仍然不確定如何設置。僅供參考除了DateTimePicker.js文件外,我還以同樣的方式嵌入了jquery-1.6.3.min.js和jquery-ui-1.8.16.custom.min.js。到目前爲止,我的DateTimePicker.js文件的內容是:$(document).ready(function(){(DatepickerInput')。datepicker({ 'dd-mm-yy' }); });你能幫我解決一些更多細節嗎? – user1041481

+0

我編輯了這些問題,爲您提供了我將用於該文件的特定代碼。 – PCasagrande

+0

太棒了,現在就開始工作吧。只需改變prm.add_endRequest(BindDatePicker()); prm.add_endRequest(BindDatePicker); – user1041481

相關問題