0

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?

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the very quick answer. I commented out my Response.Redirect() method and now my page shows alert. But i don't understand why it doesn't work with redirect method. Since the redirect method is located after alert showing method. And how I can show alert and then redirect?
You are basically injecting javascript code from the server side to show the alert. JS code executes in the client side. But you are not giving an option for the client side to load, because of the redirect in the server side. To show script and then redirect, you will have to do redirect in the client side. So together with the alert script, you have to add this code: window.location.href = "/Main.aspx"; and remove the Redirect from the server side.
I almost perfectly understood the problem and solved it. Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.