Response.Redirect() and JavaScript
Yesterday we covered issues surrounding using Response.Redirect in server side code. We noted that not handing it correctly could prevent code from running on the server that we want to run.
The other issue is emitting Javascript in the server side in association with Response.Redirect(). This also leads to unexpected problems if you aren’t thinking about what is actually happening with your code.
Take this code as an example:
protected void Page_Load(object sender, EventArgs e) { string myscript = @"<script language='javascript'> alert('hello world'); </script>"; ClientScript.RegisterClientScriptBlock ("".GetType(), "s", myscript); Response.Redirect("~/newpage.aspx",false); }
The question is, why does the javascript never display “hello world”?
Actually, the javascript is typically a little more complicated than “hello world.” But the question is always, “Why didn’t my javascript execute? It works fine without the redirect.”
Once again, we need to think more clearly about what we’ve actually written.
What we’ve actually told the server to do is the following:
- Render the javascript to display “hello world” in an alert box on the client.
- Set the header (not the header element, but the header that tells the browser whether the code executed successfully or not) to “302 redirect.”
When the browser finally gets the stream back from the server, it will actually see step 2 first because the header comes before the javascript code. The browser will look at that 302, ignore everything else on the page, and faithfully redirect to the page specified as part of the 302.
Other Related Items:
LifeSource UA-787EJ Quick Response Auto Inflate Blood Pressure Monitor with Easy-Fit Cuff, Pressure Rating Indicator and AC AdapterPressure Rating Indicator classifies your blood pressure reading30 reading memory with date/time display and 3 reminder alarmsEasyFit?? Cuff an innovative cuff that instantly fits your armClinically validated for accuracyIrregular heartbeat feature
Pro Performance Speedminton Fun SetSpeedminton, the newest high-energy sport, offers fun for every age and skill level. It sets up easily indoors or out on every type of surface. Play Speedminton without a net, you can even play in the dark.
Panasonic RP-HT21 Lightweight Headphones with XBS port for increased bass responseTake your music on the run with Panasonic's lightweight, low-cost RP-HT21 over-ear headphones. Their large, 30 mm diaphragms offer full-bodied sound f... Read More >










how to prevent this and follow the initial plan described in above steps.
Use a javascript redirect after the javascript you want to see run:
window.location = “urlToRedirectTo”;