Monday, May 10, 2010

Response.Redirect vs PostBackUrl

I normally use Response.Redirect to navigate from page to page, someone told me the other day that it would be better to use PostBackUrl of a control to redirect to a page then use Response.Redirect.

So, I ran a little test of my own, created a 2 sample pages, where on a button click I do a Response.Redirect like this.

protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Advance.aspx");
}

Next I ran Fiddler, this is the result I got on the button click, the response I get back from the server is not the content of the page I want but this...

HTTP/1.1 302 Found
Server: ASP.NET Development Server/10.0.0.0
Date: Mon, 10 May 2010 16:17:57 GMT
X-AspNet-Version: 4.0.30319
Location: /Advance.aspx
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 130
Connection: Close

Object moved to here.

Here; point to the page you want to navigate to (have to live with this HTML formating :))

The server issues a 302 and the browser issues another request to the actual page I want, so we got 2 round trips to the server.

Next< I set the PostBackUrl property of the button, and now if i see the page source, I see a javascript redirect, and if I take a look at Fiddler, on the button click, I see that there is a POST request going to the server. Now, the server returns me the page I want in just one round trip. The other advantage I get is that I can access the state of the previous page by using the PreviousPage property, all i need is to cast the return type of this property to the type of the previous page. I can access the control state from this, however you want be able to access the ViewState of the previous page from this property, but you can expose the needed view state key/value through a public property of the previous page. You can also set the %@PreviousPageType directive like this

now, you would be able to access the previous page through the PreviousPage property without having to cast into the type of the previous page.

So, in summary, use the PostBackUrl when ever you can over Response.Redirect
You would only be able to use this property with controls that implement the IButtonControl interface.

No comments:

Post a Comment