Both
Response.Redirect
and Server.Transfer
methods are used to transfer a user from one web page to another web page. Both methods are used for the same purpose, but still there are some differences as follows.
The
Response.Redirect
method redirects a request to a new URL and specifies the new URL while the Server.Transfer
method for the current request, terminates execution of the current page and starts execution of a new page using the specified URL path of the page.
Both
Response.Redirect
and Server.Transfer
have the same syntax like:Response.Redirect("UserDetail.aspx"); Server.Transfer("UserDetail.aspx");
Using the Code
When you useServer.Transfer
, then the previous page also exists in server memory while in theResponse.Redirect
method, the previous page is removed from server memory and loads a new page in memory. Let's see an example.We add some items in the context of the first page "UserRegister.aspx" and thereafter the user transfers to another page "UserDetail.aspx" usingServer.Transfer
on a button click. The user will then be able to request data that was in the context because the previous page also exists in memory. Let's see the code.Code of the UserRegister.aspx.cs page:using System; public partial class UserRegister : System.Web.UI.Page { protected void btn_Detail_Click(object sender, EventArgs e) { Context.Items.Add("Name", "Sandeep Singh Shekhawat"); Context.Items.Add("Email", "sandeep.shekhawat88@gmail.com"); Server.Transfer("UserDetail.aspx"); } }Code of the UserDetail.aspx.cs page:using System; public partial class UserDetail : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { try { Response.Write(string.Format("My name is {0} and email address is {1}", Context.Items["Name"].ToString(), Context.Items["Email"].ToString())); } catch (NullReferenceException ex) { Response.Write(ex.Message); } } }Using the code above, we can get data from the previous page to the new page by theContext.Item
collection. But if you use theResponse.Redirect
method, then you can't get context data on another page and get an exception object asnull
because the previous page doesn't exist in server memory.Figure 1.5 Null Exception by Context objectMostly theServer.Transfer
method is preferable to use becauseServer.Transfer
is faster since there is one less roundtrip, but some people say thatServer.Transfer
is not recommended since the operations typically flow through several different pages causing a loss of the correct URL of the page, but again it all depends on your requirement.It is not a complete list. I wrote the basic differences between these two. If you know more differences, then please provide them in the comments.
No comments:
Post a Comment