gpt4 book ai didi

javascript - 从 UpdatePanel 异步回发后,嵌入式 javascript 不起作用

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:50:30 27 4
gpt4 key购买 nike

我创建了一个服务器控件,其中嵌入了一些 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 中工作的任何想法?

最佳答案

UpdatePanels 使新元素在回发时被放置在页面中。它不再是同一个元素,因此您的绑定(bind)不再存在。如果您正在使用 jQuery 并将事件绑定(bind)在一起,您可以使用他们的 live API 找到 here .否则,对于诸如日期选择器之类的东西,它会触发一次并从根本上改变项目的功能,您需要在加载新元素后触发一些 javascript;所有这一切都需要将一些 javascript 调用绑定(bind)到 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'
});
};

关于javascript - 从 UpdatePanel 异步回发后,嵌入式 javascript 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8092728/

27 4 0