Wednesday, October 18, 2006

[ASP.NET] Redirecting Page after Emiting JS in Code-behind

To emit the JavaScript in code-behind in ASP.NET, we use RegisterStartupScript() or RegisterClientScriptBlock() method. But when we would like to redirect user to a specified page after the JS pop-up, we probably would use this (written in VS.NET 2003, use ClientManager for VS 2005)

string strScriptName = "AlertScript";
string strMessage = "There is an error";

string strScript += strMessage + "')<"
strScript += "/"
strScript += "script>"

objPage.RegisterStartupScript(strScriptName, strScript)


If you run the code, you will notice that you will be redirected to the error.aspx WITHOUT being prompted the error message dialog box of "This is an error" because Response.Redirect() forces the browser not to render the HTML (sending a header to client to cause client to redirect to specified URL).

To overcome this problem, replace the Response.Redirect("error.aspx"); with


Instead of redirecting the page, the browser would simply refresh the page within 0 second and "redirecting" to the error.aspx, as specified in the Url parameter.

No comments: