我已经创建了一个服务器控件,我已经嵌入了一些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);
}
}
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中使用它的任何想法?
答案 0 :(得分:4)
UpdatePanels会导致新元素在发回时放置在页面中。它不再是相同的元素,因此您的绑定不再适用。如果您正在使用jQuery并将事件绑定在一起,则可以使用live
找到的here 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'
});
};