7.1 Redirect the User to Another Page


7.1 Redirect the User to Another Page

Problem

You need to transfer execution from one ASP.NET Web page to another, or you want to redirect the user to a completely different site.

Solution

Use the HttpResponse.Redirect method to redirect the user to a new URL, or use the HttpServerUtility.Transfer method for a faster way to transfer the user to another ASP.NET Web form on the same server.

Discussion

The easiest way to redirect a user from one Web page to another is to use the HttpResponse.Redirect method and supply a new URL. You can access the current HttpResponse object through the HttpContext object or by using the Reponse property of a Page or a Control object. Here's an example of an event handler that redirects the user in response to a button click:

 private void cmdRedirect_Click(object sender, System.EventArgs e) {     Response.Redirect("newpage.aspx"); } 

The Redirect method works with relative URLs to resources in the same virtual directory, and with fully qualified URLs. URLs can point to other ASP.NET pages, other types of documents (such as HTML pages or images), and other Web servers.

The Redirect method sends a redirect instruction to the browser. The browser then requests the new page. The result is that the browser has to make two roundtrips to the Web server, and the Web server has to handle an extra request. A more efficient option is available through the HttpServerUtility.Transfer method, which transfers execution to a different ASP.NET page on the same Web server. Here's an example:

 private void cmdRedirect_Click(object sender, System.EventArgs e) {     Server.Transfer("newpage.aspx"); } 

The Transfer method doesn't require an extra trip to the client, but it won't work if you need to transfer execution to another server or another type of resource other than a Web form (including a classic ASP page).




C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net