Thứ Ba, 13 tháng 3, 2012

Server.Transfer Vs. Response.Redirect

If you read a lot of industry magazines and ASP.NET code samples, you may find that, although the majority use Response.Redirect to send the user to another page, some seem to prefer the rather mysterious-sounding Server.Transfer. So, what's the difference?
Well, Response.Redirect simply sends a message down to the browser, telling it to move to another page. So, you may run code like:
Response.Redirect("WebForm2.aspx")
or

to send the user to another page.Response.Redirect("http://www.karlmoore.com/")
Server.Transfer is similar in that it sends the user to another page with a statement such asServer.Transfer("WebForm2.aspx"). However, the statement has a number of distinct advantages and disadvantages.
Firstly, transferring to another page using Server.Transfer conserves server resources. Instead of telling the browser to redirect, it simply changes the "focus" on the Web server and transfers the request. This means you don't get quite as many HTTP requests coming through, which therefore eases the pressure on your Web server and makes your applications run faster.
But watch out: because the "transfer" process can work on only those sites running on the server, you can't use Server.Transfer to send the user to an external site. Only Response.Redirect can do that.
Secondly, Server.Transfer maintains the original URL in the browser. This can really help streamline data entry techniques, although it may make for confusion when debugging.
That's not all: The Server.Transfer method also has a second parameter—"preserveForm". If you set this to True, using a statement such as Server.Transfer("WebForm2.aspx", True), the existing query string and any form variables will still be available to the page you are transferring to.
For example, if your WebForm1.aspx has a TextBox control called TextBox1 and you transferred to WebForm2.aspx with the preserveForm parameter set to True, you'd be able to retrieve the value of the original page TextBox control by referencing Request.Form("TextBox1").
This technique is great for wizard-style input forms split over multiple pages. But there's another thing you'll want to watch out for when using the preserveForm parameter. ASP.NET has a bug whereby, in certain situations, an error will occur when attempting to transfer the form and query string values. You'll find this documented at http://support.microsoft.com/default.aspx?id=kb;en-us;Q316920.
The unofficial solution is to set the enableViewStateMac property to True on the page you'll be transferring to, then set it back to False. This records that you want a definitive False value for this property and resolves the bug.
So, in brief: Response.Redirect simply tells the browser to visit another page. Server.Transfer helps reduce server requests, keeps the URL the same and, with a little bug-bashing, allows you to transfer the query string and form variables.
Top Tip: Don't confuse Server.Transfer with Server.Execute, which executes the page and returns the results. It was useful in the past, but, with ASP.NET, it's been replaced with fresher methods of development. Ignore it.

ASP.NET 2.0's Client Callback Feature

http://drdobbs.com/windows/219501054

Script Callbacks in ASP.NET 2.0

Let's face it: Web developers would give anything for a programmable tool that would allow them to avoid page refresh. Imagine the following, rather common, scenario: You add a grid control to an ASP.NET page and make it show users a navigation bar. Whenever the user clicks to display a new set of rows, the page posts back, performs some work on the server, and then reappears identical to the previous time (except for the new set of grid rows). This process carries a significant performance hit, especially for large and complex pages. Why on earth, developers wonder, should 50 Kb of stuff have to be downloaded for each user action (and a good part of it also uploaded with the same frequency)?
Being able to update client data without causing the entire page to post back is an old dream for Web developers. Ideally, they should be able to wire up client code to call the server, execute an event, take the returned data, and update only the portion of the client page touched by the action.
ASP.NET 1.x and classic ASP enabled this function, but the developer had to accept an ActiveX control or at least a Java applet on the page to act as an intermediary. The intermediary received calls from the client's script code and set up a parallel, invisible connection to a server page. The server page got some input and returned some output. The output returned through the invisible connection was processed on the client and used to update the page via the Dynamic HTML (DHTML) object model.
ASP.NET 2.0 abstracts the developer from the creation of the request to the server and the logic needed to parse the server's response. Script callbacks in ASP.NET 2.0 offer a ready-to-use mechanism that greatly simplifies the procedure. More importantly, they hide a lot of the implementation details and shield you from a bunch of browser issues.

Script Callback Requirements


In the Microsoft world, the first implementation of callbacks was Remote Scripting (RS). RS leverages a Java applet to connect to the server and requires an ASP page to serve the request. In addition, the ASP page provides a made-to-measure object model—a sort of public and common interface—for the interaction to take place. In ASP.NET, the overall model is similar but the tools employed are different.At the core, ASP.NET script callbacks consist of some client-side JavaScript code that arranges for a programmatic roundtrip to the server. So, the first requirement for using the callbacks is that some server-side code awaits client calls. The client-side callback intermediary manages the call while the user continues to see the old page and interact with it. The callback mechanism leaves the current page unaffected and gives users the illusion that everything is taking place on the client like in a classic desktop application. Hence, the second requirement is that the browser provides DHTML capabilities and offers an advanced DOM implementation. Without these capabilities, any downloaded information would mostly be useless.

How ASP.NET Script Callbacks Work

ASP.NET callbacks use the XmlHttpRequest DOM object to set up the connection. (As far as Internet Explorer is concerned, script callbacks require at least version 5.0.) The target of the remote invocation can be either a particular server control (for example, the new GridView control) or the page itself. In general, the target must be an object that implements the ICallbackEventHandler interface.
The following paragraphs show how to enhance a page to make it support script callbacks.
The first step is identifying the HTML element that triggers the operation. Typically, this element is a button or a link that users click. It is essential that the element fires an event that is not automatically handled by the browser and results in a postback. For example, you should never use an  element to trigger the callback because  generates a submit button. The following code is fine, if you want to start the operation with a button click:

This button—an instance of the HtmlInputButton control—needs some special JavaScript code to handle the click event. You can add the following code programmatically in the Page_Load event:
callbackStarter.Attributes["onclick"] = String.Format("javascript:{0}",
       callbackRef);
How do you determine the right script code to bind? The GetCallbackEventReference function on thePage class can help. Here's an example:
string callbackRef = GetCallbackEventReference(
    this,
    "document.all['cboEmployees'].value",
    "UpdateEmployeeViewHandler", "null", "null");
The GetCallbackEventReference function's first argument indicates the target object that will handle the call on the server. If you pass this, you mean the page itself. You also can pass in a reference to any page control that implements the ICallbackEventHandler interface. In any case, the client-side submit action will hit the same ASPX page through the standard postback mechanism.
The second argument is a constant or a JavaScript expression that represents the input sent to the server. In the code above, you pass the value of the currently selected element of a drop-down list. (See the full source code.)
The third argument is the name of a user-defined JavaScript callback function defined in the