我创建了一个静态方法来在我的网站上从页面和用户控件显示一个弹出窗口。该方法不关心页面上是否有脚本管理器或更新面板。
目前该方法在以下情况下正常工作:
- 页面加载
- 页面预渲染
- 页面事件处理程序(例如 OnClick、OnSelectedIndexChanged 等)
- 用户控件加载
- 用户控制预渲染
该方法失败:
- UserControl 事件处理程序(例如 OnClick、OnSelectedIndexChanged 等)
这些列表都没有用尽。
最奇怪的部分是该方法将在用户控件的加载和预渲染事件中起作用,并在 OnClick 事件中失败。
这是静态代码:
private static Page CurrentPage
{
get
{
try
{
return (Page)HttpContext.Current.Handler;
}
catch
{
return null;
}
}
}
public static void ShowMessage(String Heading, String Message, String RedirectURL, Boolean AllowHTML)
{
if (CurrentPage != null)
{
try
{
String Script = "ShowCtMessagePopup('" + Heading + "', '" + Message + "', " + AllowHTML.ToString().ToLower() + ", " + (String.IsNullOrWhiteSpace(URL) ? "null" : "'" + URL + "'") + ");";
try
{
ScriptManager sm = ScriptManager.GetCurrent(CurrentPage);
if (sm == null || sm.IsInAsyncPostBack)
CurrentPage.ClientScript.RegisterStartupScript(typeof(System.Web.UI.Page), "ErrorMessage", Script.ToString(), true);
else
CurrentPage.ClientScript.RegisterStartupScript(typeof(System.Web.UI.Page), "ErrorMessage", "Sys.Application.add_load(function (){" + Script.ToString() + "});", true);
}
catch
{
//trouble finding script manager
CurrentPage.ClientScript.RegisterStartupScript(typeof(System.Web.UI.Page), "ErrorMessage", Script.ToString(), true);
}
}
catch
{
//ignore failed displays for now
}
}
}
这是调用代码:
<asp:Button ID="btValidate" runat="server" OnClick="btValidate_Click" Text="Validate" Width="125px" CssClass="formButton" />
protected void btValidate_Click(object sender, EventArgs e)
{
CtMessagePopup.ShowMessage("Hello", "There", null, false);
}