I have created a static method to display a popup on my website from both pages and usercontrols. The method does not care if there is a script manager or update panel on the page.
At the moment the method works correctly in:
The method fails in:
Neither of these lists are exhausted.
The strangest part is that the method will work in the load and pre render events of the user control and fail in an OnClick event.
Here is the static code:
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
}
}
}
Here is the Calling Code:
<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);
}
The solution to this issue is to use the following code:
Control Caller = this; //the user control that you are calling from
ScriptManager.RegisterStartupScript(Caller, typeof(Caller), "Script Name", Script.ToString(), true);
The Script manager has trouble adding scripts to the Page object from a user control and must have a reference to the calling user control.