client-side callback

原文链接:http://www.cnblogs.com/chiyuwang/archive/2007/02/21/653478.html Client-Side Callback
ASP.NET 2.0 includes a new client callback feature that enables you to retrieve page values and populate them to an already-generated page without regenerating the page. This makes it possible to change values on a page without going through the entire postback cycle; that means you can update your pages without completely redrawing the page. End users will not see the page flicker and reposition, and the pages will have a flow more like the flow of a thick-client application. To work with the new callback capability, you have to know a little about working with JavaScript. This book does not attempt to teach you JavaScript. If you need to get up to speed on this rather large topic, check out Wrox’s Beginning JavaScript, Second Edition, by Paul Wilton (ISBN: 0-7645-5587-1). Comparing a Typical Postback to a Callback Before you jump into some examples of the new callback feature, first look at a comparison to the current postback feature of a typical ASP.NET page.
When a page event is triggered on an ASP.NET page that is working with a typical postback scenario, a lot is going on. The diagram in Figure 4-13 illustrates the process. In a normal postback situation, an event of some kind triggers an HTTP Post request to be sent to the Web server. An example of such an event might be the end user clicking a button on the form. This
sends the HTTP Post request to the Web server, which then processes the request with the IPostbackEventHandler and runs the request through a series of page events. These events include loading the state (as found in the view state of the page), processing data, processing postback events, and finally rendering the page to be interpreted by the consuming browser once again. The process completely reloads the page in the browser, which is what causes the flicker and the realignment to the top
of the page. On the other hand, you have the alternative of using the new callback capabilities, as shown in the diagram
in Figure 4-14. In this case, an event (again, such as a button click) causes the event to be posted to a script event handler
(a JavaScript function) that sends off an asynchronous request to the Web server for processing. ICallbackEventHandler runs the request through a pipeline similar to what is used with the postback—but you notice that some of the larger steps (such as rendering the page) are excluded from the process chain. After the information is loaded, the result is returned to the script callback object. The script code then pushes this data into the Web page using JavaScript’s capabilities to do this without refreshing the page. To understand how this all works, look at the simple example in the following section.

ASP.NET Server Controls and Client-Side Scripts
Figure 4-14
Init
Load State
Process Postback Data
Load
Callback Event
Unload
Script Callback
Script Event Handler
Result
of callback
returned
Async
request
Event triggers
callback to
script event
handler
122
Chapter 4
Using the Callback Feature—A Simple Approach
Begin examining the callback feature by looking at how a simple ASP.NET page uses it. For this example,
you have only an HTML button control and a TextBox server control (the Web server control version).
The idea is that when the end user clicks the button on the form, the callback service is initiated
and a random number is populated into the text box. Listing 4-14 shows an example of this in action.
Listing 4-14: Using the callback feature to populate a random value to a Web page
.aspx page (VB version)
<%@ Page Language=”VB” AutoEventWireup=”false” CodeFile=”RandomNumber.aspx.vb”
Inherits=”RandomNumber” %>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title>Callback Page</title>
<script type=”text/javascript”>
function GetNumber(){
UseCallback();
}
function GetRandomNumberFromServer(TextBox1, context){
document.forms[0].TextBox1.value = TextBox1;
}
</script>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<input id=”Button1” type=”button” value=”Get Random Number”
οnclick=”GetNumber()” />
<br />
<br />
<asp:TextBox ID=”TextBox1” Runat=”server”></asp:TextBox>
</div>
</form>
</body>
</html>
VB (code-behind)
Partial Class RandomNumber
Inherits System.Web.UI.Page
Implements System.Web.UI.ICallbackEventHandler
Dim _callbackResult As String = Nothing;
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.Load
Dim cbReference As String = Page.ClientScript.GetCallbackEventReference(
Me, “arg”, “GetRandomNumberFromServer”, “context”)
Dim cbScript As String = “function UseCallback(arg, context)” & _
(continued)
123
ASP.NET Server Controls and Client-Side Scripts
Listing 4-14: (continued)
“{“ & cbReference & “;” & “}”
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), _
“UseCallback”, cbScript, True)
End Sub
Public Sub RaiseCallbackEvent(ByVal eventArgument As String) _
Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent
_callbackResult = Rnd().ToString()
End Function
Public Function GetCallbackResult() As String _
Implements System.Web.UI.ICallbackEventHandler.GetCallbackResult
Return _callbackResult
End Function
End Class
C# (code-behind)
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class RandomNumber : System.Web.UI.Page,
System.Web.UI.ICallbackEventHandler
{
private string _callbackResult = null;
protected void Page_Load(object sender, EventArgs e)
{
string cbReference = Page.ClientScript.GetCallbackEventReference(this,
“arg”, “GetRandomNumberFromServer”, “context”);
string cbScript = “function UseCallback(arg, context)” +
“{“ + cbReference + “;” + “}”;
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
“UseCallback”, cbScript, true);
}
public void RaiseCallbackEvent(string eventArg)
{
Random rnd = new Random();
_callbackResult = rnd.Next().ToString();
}
public string GetCallbackResult()
124
Chapter 4
{
return _callbackResult;
}
}
}
When this page is built and run in the browser, you get the results shown in Figure 4-15.
Figure 4-15
Clicking the button on the page invokes the client callback capabilities of the page, and the page then
makes an asynchronous request to the code behind of the same page. After getting a response from this
part of the page, the client script takes the retrieved value and places it inside the text box—all without
doing a page refresh!
Now take a look at the .aspx page, which simply contains an HTML button control and a TextBox
server control. Notice that a standard HTML button control is used because a typical <asp:button>
control does not work here. No worries. When you work with the HTML button control, just be sure to
include an onclick event to point to the JavaScript function that initiates this entire process:
<input id=”Button1” type=”button” value=”Get Random Number”
οnclick=”GetNumber()” />
You don’t have to do anything else with the controls themselves. The final thing to include in the page is
the client-side JavaScript functions to take care of the callback to the server-side functions. GetNumber()
is the first JavaScript function that’s instantiated. It starts the entire process by calling the name of the
client script handler that is defined in the page’s code behind. Astring type result from GetNumber()is
retrieved using the GetRandomNumberFromServer() function. GetRandomNumberFromServer() simply
populates the string value retrieved and makes that the value of the Textbox control—specified by
the value of the ID attribute of the server control (TextBox1):
<script type=”text/javascript”>
function GetNumber(){
UseCallback();
}
function GetRandomNumberFromServer(TextBox1, context){
125
ASP.NET Server Controls and Client-Side Scripts
document.forms[0].TextBox1.value = TextBox1;
}
</script>
Now turn your attention to the code behind.
The Page class of the Web page implements the System.Web.UI.ICallbackEventHandler interface:
Partial Class RandomNumber
Inherits System.Web.UI.Page
Implements System.Web.UI.ICallbackEventHandler
‘ Code here
End Class
This interface requires you to implement a couple of methods—the RaiseCallbackEvent and the
GetCallbackResult methods, both of which work with the client script request.
RaiseCallbackEvent enables you to do the work of retrieving the value from the page, but the value
can be only of type string:
Public Sub RaiseCallbackEvent(ByVal eventArgument As String) _
Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent
_callbackResult = Rnd().ToString()
End Function
The GetCallbackResult is the method that actually grabs the returned value to be used:
Public Function GetCallbackResult() As String _
Implements System.Web.UI.ICallbackEventHandler.GetCallbackResult
Return _callbackResult
End Function
In addition, the Page_Load event includes the creation and placement of the client callback script manager
(the function that will manage requests and responses) on the client:
Dim cbReference As String = Page.GetCallbackEventReference(Me, “arg”, _
“GetRandomNumberFromServer”, “context”)
Dim cbScript As String = “function UseCallback(arg, context)” & _
“{“ & cbReference & “;” & “}”
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), _
“UseCallback”, cbScript, True)
The function placed on the client for the callback capabilities is called UseCallback(). This string is
then populated to the Web page itself using the Page.ClientScript.RegisterClientScripBlock
that also puts <script> tags around the function on the page. Make sure that the name you use here is
the same name you use in the client-side JavaScript function presented earlier.
In the end, you have a page that refreshes content without refreshing the overall page. This opens the
door to a whole new area of possibilities. One caveat is that the callback capabilities described here
126
Chapter 4
use XmlHTTP and, therefore, the client browser needs to support XmlHTTP (Microsoft’s Internet
Explorer and FireFox do support this feature). Because of this, the .NET Framework 2.0 introduces the
SupportsCallBack and the SupportsXmlHTTP properties. To ensure this support, you could put a
check in the page’s code behind when the initial page is being generated. It might look similar to the
following:
VB
If (Page.Request.Browser.SupportsXmlHTTP) Then
End If
C#
if (Page.Request.Browser.SupportsXmlHTTP == true) {
}

转载于:https://www.cnblogs.com/chiyuwang/archive/2007/02/21/653478.html

上一篇:open the same code side by side with two splited windows at the same time


下一篇:ASP.NET Alerts: how to display message boxes from server-side code?