Javascript alert() after Response.Redirect

10,520

Solution 1

The way to do that is display the alert with javascript and then do the redirect with javascript as well:

ScriptManager.RegisterStartupScript(this,this.GetType(),"Redit","alert('asdf'); window.location='" + Request.ApplicationPath + "Default.aspx';",true);

Solution 2

Lets take a look at what happens when you call response.redirect()

  1. Servers sends HTTP response 302 to browser including the url to navigate to
  2. browser doesn't display content of response and instead gets the content from the url specified
  3. if the request to the new url succeeds, then it is displayed.

Now looking at this, we can deduce that it is impossible to tell the browser to do a alert() from the page that issues the redirect because its content (if any) is discarded.

It is possible to accomplish what you want from the page that you are redirecting to. To do this, just check Request.UrlReferrer to check if you were redirected from the correct page, then display the alert when appropriate.

example:

  1. Page1 redirects to page2
  2. Page2 check if Request.UrlReferrer is equal to page1
  3. If equal, display alert
  4. If not, do nothing special

Another approach is do the alert first then do the redirect from javascript. window.location.href = newurl.

Share:
10,520
Pod Mays
Author by

Pod Mays

Updated on June 07, 2022

Comments

  • Pod Mays
    Pod Mays almost 2 years

    I am calling this in my code behind:

    (test.aspx)
    Response.Redirect("~/Default.aspx");
    

    I want to include a javascript alert after/before being redirected to Default.aspx, is it possible? I'm doing this because I'm passing a value to another page (test.aspx) and that page checks the db, if reader HasRow(), then redirect to Default.aspx.