简体   繁体   中英

javascript alert and update page asp.net c#

I am writing asp.net 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?

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);
    }

It 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 complicated and requires the updating of the new page as well.

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';");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM