![](/img/trans.png)
[英]Javascript event subscription after UpdatePanel async postback
[英]Embedded javascript does not work after async postback from UpdatePanel
我已經創建了一個服務器控件,我已經嵌入了一些JavaScript文件。 這可以正常工作,但是當服務器控件放在ajax UpdatePanel中時,它會在updatepanel中觸發異步回發后停止工作。
這是我在服務器控件中的代碼:
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);
}
}
在異步回發上執行此代碼的位置:
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中使用此功能的任何想法?
UpdatePanels會導致新元素在發回時放置在頁面中。 它不再是相同的元素,因此您的綁定不再適用。 如果您正在使用jQuery並將事件綁定在一起,則可以使用此處的live
API。 否則,對於諸如datepickers之類的東西,它會觸發一次並從根本上改變項目的功能,一旦加載新元素,你需要激活一些javascript; 所有這些都需要將一些javascript調用綁定到Microsoft提供的回調函數:
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'
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.