Reputation: 6188
I want to show a Javascript when user submit a page. I am calling this Javascript through code behind (I think this was easy). Here is my code:
MessageBox1("Testing my Message"); //Calling Function!
private void MessageBox1(string msg) //This is in the code behind of the page.
{
// Cleans the message to allow single quotation marks
string cleanMessage = msg.Replace("'", "\\'");
string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";
// Gets the executing web page
Page page = HttpContext.Current.CurrentHandler as Page;
// 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(CommSetup), "alert", script);
}
}
This is not working...What I am doing wrong here? Thank you!
Upvotes: 0
Views: 1840
Reputation: 3539
Use this static method to pop the alert:
public static void JS_Alert(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 = HttpContext.Current.CurrentHandler as Page;
// 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(Utilities), "alert", script);
}
}
EDIT: "Utilities" should be the name of the class you place this method in. Mine happens to be called Utilities. If your putting it in the code-behind partial class, its usually called whatever your web page is called with .cs on the end.
Upvotes: 1
Reputation: 50728
Instead of using a Literal, use the ClientScriptManager:
Page.ClientScriptManager.RegisterStarupScript("startup",
"<script language='javascript'>window.location=''; window.alert('" + msg.Replace("'", "\\'") + "') </script>", false);
I forget exactly how many parameters are required, but it would look something like this. If using a ScriptManager, there also is:
ScriptManager.RegisterStartupScript(this.GetType(), "startup", ..);
too.
HTH.
Upvotes: 2