0

这是我的代码,我在其中注册了一个脚本块以显示来自我的 C# 类的 Javascript 警报:

public static void MessageBox(string strMessage)
{
    // Gets the executing web page
    Page page = HttpContext.Current.CurrentHandler as Page;

    string script = string.Format("alert('{0}');", strMessage);

    // Only show the alert if it's not already added to the 
    if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
    {
        page.ClientScript.RegisterClientScriptBlock(page.GetType(), "alert", script, true /* addScriptTags */);
    }
}

当我在 DOM 完全加载之前MessageBox调用该函数时,这非常有用。但是,当我在 DOM 完全加载后动态调用此函数(例如:如果用户点击提交并捕获错误)时,不会弹出警报。

为什么我在 DOM 完全加载之前的初始调用有效,而在 DOM 加载进行的相同调用不起作用?

编辑:

在查看评论中的以下链接后,我试了一下:

Page page = HttpContext.Current.CurrentHandler as Page;
ScriptManager.RegisterClientScriptBlock(page, typeof(Page), "MyScript", "alert('heyyyyyy');", true);

虽然ScriptManager应该用于处理 AJAX 调用,但这会产生与我上面最初的尝试相同的结果。Javascript 警报在初始页面加载时弹出,但不再弹出(在我的任何 AJAX 请求上)。

编辑(2):

这是我的MessageBox功能:

public static void MessageBox(string strMessage)
{
    Page page = HttpContext.Current.CurrentHandler as Page;
    ScriptManager.RegisterClientScriptBlock(page, typeof(Page), "MyScript", "alert('heyyyyyy');", true);
}

这是我称之为的一个地方:

public static string GetLoggedOnUserId(string strLogonUser)
    {
        string strUserId = string.Empty;

        try
        {
            MessageBox("hey");
            int intPositionOfSlash = strLogonUser.IndexOf("\\");
            strUserId = strLogonUser.Substring(intPositionOfSlash + 1, 6).ToUpper();
        }
        catch (Exception ex)
        {
            ErrorHandler('B', ex);
        }

        strLoggedOnUser = strUserId;
        return strUserId;
    }

这个调用会弹出警报(因为它是在第一页加载时)。

这是我第二次尝试调用该MessageBox函数:

public static string LoadListItems(string strListItemStoredProcedureName, string strConnectionString)
{
    try {
        string strSQLQuery = " EXE " + strListItemStoredProcedureName.Trim() + " ";
        SqlCommand objCommand = new SqlCommand(strSQLQuery, objConnection);
        // other code here...
    }
    catch (Exception ex) {
        MessageBox("error");
    }
}

此调用不会弹出警报...请记住,此函数是通过 AJAX 帖子调用的 - 不是在页面重新加载时。

4

1 回答 1

1

我最终使用了我在这里找到的一个类:http ://www.c-sharpcorner.com/uploadfile/mahesh/webmsgbox09082006110929am/webmsgbox.aspx

无论我是否在页面加载、卸载、AJAX 调用等,这都有效。您调用的简单类使用:

WebMsgBox.Show("Your message here");

于 2013-11-05T14:56:53.470 回答