saidfagan
saidfagan

Reputation: 841

How to show JavaScript alert on button click event in asp.net?

I have a simple asp.net WebForms app with two forms: Main.aspx and Card.aspx. In the Card form I have save button which has the following click event:

    protected void buttonSave_Click(object sender, EventArgs e)
    {
        if (canSave)
        {
            string script = String.Format("alert(\"{0}\");", "Successfully saved");
            ScriptManager.RegisterStartupScript(this, this.GetType(), "alertMessage", script, true);
            Save();
            Response.Redirect("~/Main.aspx");
        }
    }

So, it should show an alert, save data (Save() method) and redirect to the Main form. Eventhough, it saves data and redirects to the page, it doesn't show an alert. The code that should show an alert works on the page load event but not on the button click event. What is the reason?

Upvotes: 0

Views: 1432

Answers (1)

Boney
Boney

Reputation: 2202

Script executes in the client side of Card.aspx. Since in the server side itself you do a redirect to Main.aspx, script doesn't execute and hence doesn't show the alert.

Script works in the PageLoad event, since there is no redirect happening.(I'm assuming since the code is not provided for PageLoad)

Upvotes: 1

Related Questions