Home

ASP ADVANCED

In a number of situations, you need to redirect a user to another page.  For example, if a user attempts to access a page that requires registration, the user should automatically be redirected to a registration page.  Or if the user has entered incomplete form information, he or she should automatically be redirected to the page with the form so that it can be completed.

It's very easy to redirect a user to a new page using Active Server Pages.  The Redirect method of the Response object allows you to redirect a user to a new page.  Look at this example:

<%
If Request.Form("FirstName")=" " THEN Response.Redirect "/register.asp"
%>
<HTML>
<HEAD><TITLE> Registration Results </TITLE></HEAD>
<BODY>
Thank you <%=Request.Form("FirstName")%> for registering!
</BODY>
</HTML>

Imagine that a user has just completed a registration form and this page is returned.  The Response.Redirect method, in this example, is used to redirect the user back to the page with the registration form if the user hasn't entered a first name.

You must use the Response.Redirect method before any text is outputted to the browser.  Therefore, it's a good idea to place this method in a script that appears above the <HTML> tag.  The only way around this requirement is to buffer the output of your Active Server Page (see the section "Buffering Output" to learn how to do this).

You can use the Response.Redirect method to redirect a user to any valid URL.  This could be another page on your Web site or even a page located at another Web site on the Internet.  The Response.Redirect method is potentially a very useful method.  Microsoft uses this method extensively in its demonstration applications for Active Server Pages.  Sadly, however, there are problems with it.  The Response.Redirect method works by returning a particular status code. Whenever a server responds to a request, the server returns a status code in the first line of its response.  When the Response.Redirect method is called, the status code 302 Object moved is returned.  A location header is also added to the response to give the new location of the page.  The status code and location header should automatically redirect the browser to the new page.

In reality, however, this doesn't always happen.  Older browsers in particular have problems with redirection.  Worse yet, even very recent browsers such as Netscape Navigator 4.0 can have difficulties automatically responding to the redirection status code.  When a browser can't respond automatically to a status code, you receive a message like that --

Object Moved

This object may be found here

This message isn't pretty, and can lead to confusion.  For this reason, you should try to avoid using the Response.Redirect method.  Use the simulated redirect method discussed in the next section instead.