在ASP.NET应用程序中使用母版页时注册客户端脚本块时出错
本文关键字:注册 客户端 脚本 出错 母版页 NET ASP 应用程序 | 更新日期: 2023-09-27 18:26:02
我从Mads Kristensen的博客中得到了这段代码,它使用Javascript在ASP.NET客户端的页面上显示一个消息框:
public static class Alert
{
public static void Show(string message)
{
// Cleans the message to allow single quotation marks
string cleanMessage = message.Replace("'", "'''");
string script = "<script type='"text/javascript'">alert('" + cleanMessage + "');</script>";
// Gets the executing web page
Page page = (Page)HttpContext.Current.CurrentHandler;
// Checks if the handler is a Page and that the script isn't allready on the Page
if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
{
page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script, false);
}
}
}
当没有涉及母版页时,它工作得很好。然而,当我从母版页派生的页面调用它(在服务器端)时,它不起作用。我猜它与RegisterClientScriptBlock()方法有关,但我不知道是什么。有人能告诉我解决这个问题的方法吗?
为了防止有人发现这一点,我找到了解决问题的方法。碰巧我的主页在UpdatePanel中有ContentPlaceHolder标记,所以当我替换时:
page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script, false);
签字人:
ScriptManager.RegisterStartupScript(page, page.GetType(), "alert", script, false);
警报消息框开始显示在所有页面上。