I am writing asp project in C#.
I have a button in a page default.aspx, and I need javascript alert when I click the button and then update page. I do this by the following way:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("<script language='javascript'>alert('OK');</script>");
Response.Redirect("default.aspx");
}
But javascript alert doesn't occur. So, how to make first appear javascript alert and then update page?
I am writing asp project in C#.
I have a button in a page default.aspx, and I need javascript alert when I click the button and then update page. I do this by the following way:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("<script language='javascript'>alert('OK');</script>");
Response.Redirect("default.aspx");
}
But javascript alert doesn't occur. So, how to make first appear javascript alert and then update page?
Share Improve this question asked Jul 17, 2012 at 9:30 NurlanNurlan 2,96020 gold badges49 silver badges65 bronze badges4 Answers
Reset to default 3It is not working because you are calling the Response.Redirect
. Anything that happens before this on the current page will be ineffective, because the new page will immediately redirect before the current page is rendered.
You have a couple of options, but the one I think you want is this...
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("<script type='text/javascript'>");
Response.Write("alert('OK');");
Response.Write("document.location.href='default.aspx';");
Response.Write("</script>");
}
The other option is to store the message you want to display in something like a session variable, and then show it on the new page after the redirection - but that is more plicated and requires the updating of the new page as well.
try this:
protected void Page_Load(....)
{
this.myButton.Attributes.Add("onclick", "alert('OK'); return true;");
}
Or in the ASPX
<asp:Button runat="server" ID="myButton" onClientClick="alert('OK'); return true;" ... />
To execute the code after you have processed something on the server try the following:
ASPX
<asp:ScriptManager runat="server" ID="scriptManager" />
<asp:Button Text="text" runat="server" OnClick="dd_Click" />
Code behind
protected void dd_Click(object sender, EventArgs e)
{
// add your cool stuff
ScriptManager.RegisterStartupScript(this, typeof(RelatedUpdatePanels), "myKey", "alert('OK');window.location='newurl.aspx';", true);
}
try following
protected void Button1_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "<script language='JavaScript'>alert('OK'); window.location.href = 'Default.aspx';</script>");
}
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "alert('Invalid username or password'); document.location.href='Default.aspx';");
OR
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "alert('Invalid username or password'); window.location.href='Default.aspx';");