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

ASP.NET C#中GridView内ScriptManager弹窗不显示问题求助

问题原因与修复方案

核心问题

  • 你的GridView嵌套在UpdatePanel内,触发的是异步回发,而ClientScript.RegisterClientScriptBlock仅支持同步回发场景,无法将脚本注入到UpdatePanel的异步响应流中,导致弹窗无法触发。
  • 你原本使用的window.onload在异步回发后不会再次执行,因为页面初始加载已经完成,这也是弹窗不显示的额外原因。

修复步骤

  1. 替换ClientScript.RegisterClientScriptBlock为ScriptManager.RegisterClientScriptBlock——这是ASP.NET专门用于处理异步回发场景的脚本注册方法。
  2. 移除window.onload包裹,直接执行alert语句,确保异步回发完成后立即触发弹窗。
  3. 利用ScriptManager.RegisterClientScriptBlock的最后一个参数addScriptTags,设为true时无需手动拼接<script>标签,简化代码。

修正后的完整代码

protected void rptHotoIPDataInfo_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    Label id = rptHotoIPDataInfo.Rows[e.RowIndex].FindControl("lbl_ID") as Label;
    TextBox txt_Remarks = rptHotoIPDataInfo.Rows[e.RowIndex].FindControl("txtRemarks") as TextBox;

    string strID = id.Text;
    string strRemarks = txt_Remarks.Text;
    string rejected_by = CurrentUserName;
    string rejected_group_id = ddlApprovalStatus.SelectedValue;

    var splitValue = rejected_group_id.Split('-');
    var middleValue = splitValue[1];

    bool updateData = false;

    if (id != null)
    {
        if (!string.IsNullOrEmpty(strRemarks))
        {
            updateData = UpdateRejectInfo(strID, strRemarks, rejected_by, middleValue);

            if (updateData)
            {
                rptHotoIPDataInfo.EditIndex = -1;
                BindHotoIPNonIPSubmit();
            }
        }
        else
        {
            // 使用ScriptManager注册兼容异步回发的弹窗脚本
            string message = "Remarks cannot be blank";
            ScriptManager.RegisterClientScriptBlock(
                this, 
                this.GetType(), 
                "alertMessage", 
                $"alert('{message}');", 
                true // 自动生成<script>标签
            );
            // 阻止GridView完成更新流程,保持当前行的编辑状态
            e.Cancel = true;
        }
    }
}

额外优化点

  • 用string.IsNullOrEmpty(strRemarks)替代strRemarks != "",能同时处理null和空字符串两种异常情况,逻辑更严谨。
  • 添加e.Cancel = true,当备注为空时,阻止GridView退出编辑模式,方便用户直接补充内容,提升交互体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 15:31:10