: Xuanyuan South Palace
One of the main reasons for developers to use JavaScript is to avoid page refreshing during the sending-back process. For example, you can use the Treeview control to expand and collapse corresponding data nodes as needed. When you expand a node, the Treeview control will use JavaScript to read information about subnodes on the server, and then smoothly Insert new nodes without any additional traffic. If JavaScript is not used, the Treeview control will be re-built due to the page sending back. Not only will the user find the latency caused by PAGE refreshing, but the page is very likely to return to the original state, that is, the information of the Child Nodes expanded above will be lost. For the server side, a large amount of View State information must be processed during each send-back process, which seriously affects the overall execution performance of the program.
The JavaScript examples we used previously are almost all self-contained, that is, they are usually used to complete some special display effects (for example, a new page window pops up ), without information interaction with the server code. If you want to build a similar page without refreshing, you must first call a specific method on the server side. After the server responds, the request information will be transmitted to the client, this avoids sending back. To implement this scheme, you must first have a general understanding of how to communicate client scripts with server code. Although there are many ways to achieve the interaction between the two (such as calling Web Services), due to the limitations of specific browsers and platforms, their implementation is still difficult. In ASP. NET 2.0 introduces a function called "client callback". With this built-in solution, we can easily implement interaction between client scripts and server code, this avoids frequent page refresh due to sending back.
In essence, client callback refers to sending the corresponding data parameters to the server through the client script at the front end, and then querying and processing the received parameters at the server end, finally, the results are uploaded back to the client for display. Although such a process is not a kind of innovation, for many developers, this is still incomprehensible in some way, because of the memory management and. net clr memory management is a different process, and the management space is also completely different, so there is no direct reference or direct interaction between each other, the client callback is one of the methods to implement communication between the client and the server, and because it is triggered on the client, it should be named "client callback!
Create a simple client callback
To display a client callback instance in ASP. NET, we will first outline how the interaction process between client Callbacks is implemented. The basic steps are as follows:
1. Activate a JavaScript event at a certain time to trigger the client callback.
2. After the client callback is triggered, a method on the server side will be executed. This method has a fixed pattern-it accepts a string parameter and returns a string parameter.
3. Once the page receives the response results from the server method, it can use JavaScript to modify some information related to the User Interface (for example, display the returned results on the page)
For developers, the underlying interaction process is very complex, ASP. NET abstracts the interaction processing process, so that developers can directly establish a client callback on the surface, without considering how the underlying operations are implemented.
In the following example, a text box, a submit button, and a label are placed on the page. The text box is used to accept user input information. After you click the submit button, the information entered in the text box is displayed on the tab in real time. Note: When you click the submit button after entering the information, the page is not rebuilt and refreshed as in the traditional submission method. Figure 1-1 shows the instance.
Create basic page
Drag a TextBox Control and a Label control to the main form in the standard Label of the toolbar according to the layout. Drag an InputButton HTML button in the "HTML" tag. Note that this button is not a server-side control that we often use, but an HTML element. Add an onclick event to the button. Click this button to send a callback request to the server. The implementation details of this onclick event will be described later. The initial Page code is as follows:
<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "CallBackExample. aspx. cs" Inherits = "CallBackExample" %>
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> client callback </title>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div>
Enter the following information: <asp: TextBox ID = "txtEnter" runat = "server"> </asp: TextBox>
<Input id = "btnSubmit" type = "button" value = "Submit" onclick = "CallServer (txtEnter, lblShow)"/>
<Br/>
<Asp: Label ID = "lblShow" runat = "server"> </asp: Label>
</Div>
</Form>
</Body>
</Html> |
Execute callback
To implement client callback, you must implement an ICallbackEventHandler interface in the page logic code. The Code is as follows:
Public partial class CallBackExample: System. Web. UI. Page,
System. Web. UI. ICallbackEventHandler
{... ...} |
The ICallbackEventHandler interface defines two methods. RaiseCallbackEvent () accepts a string from the browser as the event parameter, that is, this method accepts the parameters passed by the client JavaScript. Note that it is triggered first. The GetCallbackResult () method is triggered next. It returns the result to the JavaScript of the client, and then updates the result to the page.
In this example, the parameters in RaiseCallbackEvent () are our input information in the text box. To indicate that it is returned from the server, we add descriptive text. Then, use the GetCallbackResult () method to return the result to the client. The complete page logic code is as follows:
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 CallBackExample: System. Web. UI. Page,
System. Web. UI. ICallbackEventHandler
{
// Define a string. The callback result is saved in the string.
Private string result;
// Handle callback events
Public void RaiseCallbackEvent (string eventArgument)
{
// "EventArgument" is the parameter passed from the client's JavaScript
Result = "content returned from the server:" + eventArgument;
}
// Return the callback result
Public string GetCallbackResult ()
{
Return result;
}
} |
Write client scripts
Client scripts are mainly used to interact information between the server and the client. In this example, we used the eventArgument parameter in the previous page logic code, how does this implement parameter transfer? We will discuss it in a later chapter, and add the following JavaScript function code to the page.
Function CallServer (inputcontrol, context)
{
// Display value pre-loaded when the callback has not been fully processed
Context. innerHTML = "loading ......";
// The information you enter in the text box, and arg transmits its value
// In eventArgument corresponding to the RaiseCallbackEvent (String eventArgument) Method
Arg = inputcontrol. value;
// Obtain a reference to the client function. When this function is called, a client callback for server-side events is started.
<% = ClientScript. GetCallbackEventReference (this, "arg", "eseserverdata", "context") %>;
} |
In the above JavaScript function code, we reference A ClientScript. GetCallbackEventReference (......) Method. What functions does this method implement? The following is an excerpt from ClientScript. GetCallbackEventReference (…) on MSDN2 (......) .
Public string GetCallbackEventReference (Control control, string argument, string clientCallback, string context)
Parameters:
| Parameters |
Function |
| Control |
The server that processes the client callback. This control must implement the ICallbackEventHandler interface and provide the RaiseCallbackEvent method. |
| Argument |
Transmits a parameter from the client script to the RaiseCallbackEvent method on the server. |
| ClientCallback |
The name of a client event handler that receives the results returned by server events. |
| Context |
Client script information on the client before the callback is started. The script result is returned to the client event handler. |
| Return Value |
The name of the client function that calls the client callback. |
The following is an overloaded list of the ClientScriptManager. GetCallbackEventReference method.
| Name |
Description |
| ClientScriptManager. GetCallbackEventReference (Control, String) |
Gets a reference to a client function. When this function is called, a client callback for server-side events is started. The client function of this overload method contains the specified controls, parameters, client scripts, and context. |
| ClientScriptManager. GetCallbackEventReference (Control, String, Boolean) |
Gets a reference to a client function. When this function is called, a client callback for server-side events is started. The client function of this overload method contains the specified controls, parameters, client scripts, context, and boolean values. |
| ClientScriptManager. GetCallbackEventReference (Control, String, Boolean) |
Gets a reference to a client function. When this function is called, a client callback for server-side events is started. The client functions of this overload method include the specified controls, parameters, client scripts, context, error handlers, and boolean values. |
| ClientScriptManager. GetCallbackEventReference (String, Boolean) |
Gets a reference to a client function. When this function is called, a client callback for server-side events is started. The client function of this overload method contains the specified target, parameter, client script, context, error handler, and Boolean value. We will give a systematic description of the entire program and list the Page code at the front end and the logic code at the back end. This gives you an intuitive understanding of the program. |
Background code CallBackExample. aspx. cs
Code Description:
To successfully run the server code from the client without sending back, you must implement an appropriate interface in the Server Page code. Therefore, we declare the ICallbackEventHandler interface in the code of Line 3. Lines 15th and 19 create two server-side code callback methods. Where is the "eventArgument" string parameter in the "RaiseCallbackEvent ()" method of Row 3? When you go to the front-end page with the code line 10th, arg is equivalent to the real parameter passed to the "RaiseCallbackEvent ()" method. The "GetCallbackResult ()" method of Row 3 returns the result obtained through the "RaiseCallbackEvent ()" method to the client, the result "result" is finally passed to the "result" parameter of the "eseserverdata ()" method shown in code 15th on the foreground page.
Front-end code CallBackExample. aspx
Code Description:
To send the echo and receive results to the server page, we define two client script functions on the front-end page. The "CallServer ()" function shown in row 7th implements the callback sending function. Note that the callback sending function is actually implemented on the server side, this is because the "ClientScript" of 11th rows is actually implemented for sending callback. getCallbackEventReference () "method, while the" CallServer () "function is only for" ClientScript. getCallbackEventReference () "method reference, and provide some necessary parameters.
Now let's explain in detail the specific implementation details of these client functions. by clicking the button declared in lines 25th and 26 on the page, The OnClick event will be triggered.
After passing the text box and label as parameters to the corresponding JavaScript function of row 7th in "CallServer ()", "inputcontrol" and "context" are like the form parameters of the text box and label control. The Code in line 9th indicates that "context" will display a "loading ...... ", The callback result is re-displayed with" context "only after the callback is complete with the code of line 17th. The Code in line 10th grants "arg" to the input value of the text box, and "arg" serves as the corresponding 12th parameter in the ClientScript. GetCallbackEventReference () method of the Code in line 2nd. The first parameter uses "this" to indicate reference to this page, because the ClientScript. GetCallbackEventReference () method is also implemented in CallBackExample. aspx. The third parameter indicates the client function that receives the callback result. It matches the ReceiveServerData () function implemented by the 15th-line code (note that the function name must be consistent, otherwise, an error occurs.) The callback result is displayed through "context. The fourth parameter "context" is used to return the context from the server, because ClientScript. the GetCallbackEventReference () method is executed on the server. In this method, the "context" content originally passed is a "loading ...... "Information. After the callback is returned," context "is rewritten in row 17th. If there is no reference to the context, you can set this parameter to" null ".
Client callback program for reading database information
This program is used to read the Emlpoyees information of the Northwind database. Therefore, you must first ensure that the Northwind database exists. Is the content of the Emlpoyees table.
Enter the username to be searched in the text box, and then click "Callback". A client callback occurs. This is the display result of the user.
|
This is the display result of the user. |
Display information that does not exist for the user:
|
Display information that does not exist for the user |
Background code: ClientCallbacksSimple. aspx. cs
01 using System;
02 using System. Data;
03 using System. Configuration;
04 using System. Collections;
05 using System. Web;
06 using System. Web. Security;
07 using System. Web. UI;
08 using System. Web. UI. WebControls;
09 using System. Web. UI. WebControls. WebParts;
10 using System. Web. UI. HtmlControls;
11 using System. Data. SqlClient;
12 public partial class ClientCallbacksSimple: System. Web. UI. Page, 13
13 System. Web. UI. ICallbackEventHandler
14 {
15 protected string strUserInfo; // Save the read user information
16 // triggers a callback event
17 public void RaiseCallbackEvent (string txtFirstName)
18 {
19 if (txtFirstName! = Null)
20 {
21 SqlConnection conn = new SqlConnection ("data source = localhost; initial
22 catalog = Northwind; integrated security = SSPI ");
23 conn. Open ();
24 SqlCommand cmd = new SqlCommand ("select EmployeeID, FirstName, City, Address 25
25 from Employees where FirstName = @ FirstName ", conn );
26 cmd. Parameters. Add ("@ FirstName", SqlDbType. NVarChar, 10). Value = txtFirstName;
27 SqlDataReader dr = cmd. ExecuteReader ();
28 if (dr. Read ())
29 {
30 strUserInfo = "employee code:" + dr ["EmployeeID"] + "\ r \ n ";
31 strUserInfo + = "name:" + dr ["FirstName"] + "\ r \ n ";
32 strUserInfo + = "City:" + dr ["City"] + "\ r \ n ";
33 strUserInfo + = "Address:" + dr ["Address"]. ToString (). Replace ("\ r \ n", "") + "\ r \ n ";
34 strUserInfo + = "Server Query time:" + DateTime. Now. ToLongTimeString ();
35}
36 else
37 {
38 if (String. IsNullOrEmpty (txtFirstName ))
39 {
40 strUserInfo = "enter your name ";
41}
42 else
43 {
44 strUserInfo = "No such person found ";
45}
46}
47 cmd. Dispose ();
48 dr. Dispose ();
49 conn. Dispose ();
50}
51}
52 // return the callback result
53 public string GetCallbackResult ()
54 {
55 return strUserInfo; // return the basic information of the employee
56}
57} |
Code Description: In the RaiseCallbackEvent () method, an input data from the text box on the foreground page is passed as its parameter, that is, the user name to be queried from the database. Line 28-34 provides the function of reading user details and saving user information in a string strUserInfo. If the user cannot be found, some error messages are returned. For details, see Code 36-45. The callback result of the GetCallbackResult () method, that is, the string that saves the user information.
Front-end code: ClientCallbacksSimple. aspx
01 <% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "ClientCallbacksSimple. aspx. cs"
02 Inherits = "ClientCallbacksSimple" %>
03 04 05 <title> client callback program for reading database information </title>
06 <script type = "text/JavaScript">
07 function OnCallback (strUserInfo, context)
08 {
09 Results. innerText = strUserInfo;
10}
11 </script>
12
13 <body>
14 <form id = "form1" runat = "server">
15 <div>
16 name: <input id = "txtUserName" type = "text"/>
17 <input id = "btnCallback" type = "button" value = "Callback" onclick = "<% =
18 ClientScript. GetCallbackEventReference (this, "document.form1.txt UserName. value ",
19 "OnCallback", null) %> "/>
20 <br/>
21 <div ID = "Results" style = "background-color: pink"> </div>
22 </div>
23 </form>
24 </body>
25 |
Code Description: The biggest difference between this program and the first program is the slight difference on the front-end page. As shown in code 17-19, the ClientScript. GetCallbackEventReference () method for sending callback is directly written in the Click Event of the button. This is also a feasible and simple method. ClientScript. the three parameters of the GetCallbackEventReference () method are "OnCallback", indicating that the callback result is returned to the OnCallback () Script Function of the client after the callback is complete, the callback result strUserInfo is displayed on the page as a parameter of the function, as shown in code 9. ClientScript. the four parameters of the GetCallbackEventReference () method are "null", but the OnCallback () Script Function still needs to retain the "context" parameter, because this is the fixed format of the client function that accepts the callback result.
Summary:
Note that all asynchronous technologies, such as the Callback client Callback discussed in this article, and the new Atlas framework launched by Microsoft, do not use the traditional Postback. Therefore, when the client presents the data returned by the server, the browser cannot see a transient green state bar, And the asynchronous process only transmits and accepts a small amount of data, instead of the entire ViewState passed in the Postback process, the execution performance of the program is greatly improved. It is hoped that the reader can patiently understand and practice the two examples above, and can understand the essence of client callback only through his own practice.