You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在UpdatePanel内基于document.ReadyState调用JavaScript函数?

解决UpdatePanel异步加载GridView后执行JavaScript的问题

问题根源

你当前的JavaScript代码依赖document.onreadystatechange和window.onload事件,但这两个事件仅在整个页面首次加载时触发。UpdatePanel的异步回发是局部页面更新,不会触发这些全局加载事件,所以代码无法执行。


解决方案1:后台注册启动脚本(推荐)

在GridView绑定完成后,通过ScriptManager直接注册需要执行的JavaScript代码,异步回发完成后客户端会自动执行这段代码。

修改后台ButtonLoadGridView_Click代码:

protected void ButtonLoadGridView_Click(object sender, EventArgs e)
{
    GridView1.DataSource = dsData; // 注意原代码中dsData的引号需移除,它是数据源对象
    GridView1.DataBind();

    // 注册要执行的JavaScript
    string script = $@"
        document.getElementById('{Label_Clients.ClientID}').scrollIntoView({ behavior: 'smooth' });
        alert('Your data is loaded');
    ";
    ScriptManager.RegisterStartupScript(this, GetType(), "GridViewLoadedScript", script, true);
}

解决方案2:客户端监听UpdatePanel异步完成事件

通过ASP.NET内置的PageRequestManager对象,监听异步回发结束事件,在事件回调中执行目标代码。

添加到页面的JavaScript代码:

// 监听UpdatePanel异步回发完成事件
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(sender, args) {
    // 检查GridView是否存在,确保异步回发是加载GridView的操作
    var gridView = document.getElementById('<%= GridView1.ClientID %>');
    if (gridView) {
        document.getElementById('<%= Label_Clients.ClientID %>').scrollIntoView({ behavior: 'smooth' });
        alert('Your data is loaded');
    }
});

注意事项

  • 解决方案1更精准,仅在GridView绑定完成后执行代码;
  • 解决方案2会在所有UpdatePanel异步回发完成后触发,若需针对特定按钮触发,可通过sender._postBackSettings.panelID或检查触发控件ID来过滤。

内容的提问来源于stack exchange,提问作者Laurent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 05:35:15