Implementation analysis of ASP.net 2.0 client callback

Source: Internet
Author: User
Tags contains implement reference xmlns
One of the main reasons for asp.net| client developers to use JavaScript is to avoid page refreshes that are brought in by the postback process. For example, we can use the TreeView control to expand and collapse the corresponding data node according to the needs of the user. When you expand a node, the TreeView control will use JavaScript to read the child node information on the server, and then insert the new nodes smoothly without flushing. If you do not use JavaScript, the TreeView control will be rebuilt because of a page postback. Not only the user will find the delay caused by the page refresh, and the page is very likely to revert to the original state, that is, the loss of the previous expansion of those child nodes information. For the server side, because a large number of view state information is processed during each postback, this can also seriously affect the overall performance of the program.

The JavaScript examples we used previously were almost self-contained, that is, they are usually designed to perform some special display effects (such as popping a new page window) without interacting with the server-side code. If you also want to build a similar no refresh page, you must first call a specific method on the server side, waiting for the server to respond to the requested information will be passed to the client, thereby avoiding the process of postback. To implement this scenario, you first need to have a general idea of how to communicate client script and server-side code. Although there are many ways in which you can interact with each other (such as invoking a Web service), they are still difficult to implement due to the limitations of specific browsers and platforms. In ASP.net 2.0, a feature called "Client Callback" was introduced, and with this built-in solution we were able to easily interact between client-side and server-end code, thus avoiding the frequent refresh of the page due to postback.

Pole Development asp.net column: http://dev.yesky.com/msdn/msdnasp/

The client callback essentially refers to passing the corresponding data parameter to the server by the front-end client script, and the server end is queried and processed by the accepted parameters, and finally the result is uploaded to the client for display. While such a process is not a pioneering undertaking, it is somehow incomprehensible to many developers because the memory management of JavaScript and the memory management of the. NET CLR are different processes, and the management space is distinct, So there is no direct reference to each other and there is no direct interaction between the way, and the client callback is the implementation of the client and server side of the method of communication, and because it is triggered on the client, so this should be "client callback" The origin of the name!

   to create a simple client callback

In order to present an instance of a client callback in ASP.net, we will first outline how the interaction between client callbacks is implemented. The following are the basic steps:

1. Activates a JavaScript event at some point, triggering a client callback.

2. When a client callback is triggered, a method on the server side is executed. The method has a fixed pattern-it accepts a string parameter and returns a string parameter.

3. Once the page is affected by the response from the server-side method, it can use JavaScript to modify some of the information related to the user interface (for example, display the results returned on the page)

For developers, the underlying interaction process is very complex, ASP. NET abstracts the process of interaction so that developers can directly create surface-level client callbacks without having to consider how the underlying operations are implemented.

In the following example, a text box, a Submit button, and a label are placed in the page. A text box is used to accept input from a user, and after clicking the Submit button, the information entered in the text box is displayed in real time on the label. Note that when you click the Submit button after entering the information, you do not have to rebuild and refresh the page as you did in previous traditional submissions. Figure 1-1 illustrates the effect of the instance.




   Create a basic page

Drag a TextBox control, a Label control, onto the main form in the Standard tab of the toolbar, as shown in the diagram above. Then drag and drop a Inputbutton HTML button in the HTML tab, and note that the button is not a server-side control that we often use, but an HTML element. Add an OnClick event to the button, click the button this will issue a callback request to the server side, and the details of the implementation of the OnClick event will be explained in a later procedure. The resulting initial page code is as follows:

<%@ Page language= "C #" autoeventwireup= "true" codefile= "CallBackExample.aspx.cs" inherits= "Callbackexample"%>
<title> Client Callback </title>
<body>
<form id= "Form1" runat= "Server"
<div>
Please enter information: <asp:textbox id= "Txtenter" runat= "Server" > </asp:TextBox>
<input id= "btnsubmit" type= "button" value= "Submit"/>
<BR/>
<asp:label id= "lblshow" runat= "Server" > </asp:Label>
</div>
</form>
</body>
   Execute callback

In order to implement the client callback, you must implement a ICallbackEventHandler interface in your 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 () takes a string from the browser as an event parameter, that is, the method accepts the parameters passed by the client JavaScript and notices that it is triggered first. The next trigger is the GetCallbackResult () method, which passes the resulting results back to the client's javascript,javascript and updates the results to the page.

The arguments in the raisecallbackevent () in this example are the input information for our text boxes. To show that it was returned from the server, we added some descriptive text. The results are then passed back to the client using the GetCallbackResult () method. 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
{
Defines a string, and the result information for the callback is saved in the string
private string result;

Raise callback Event handling
public void RaiseCallbackEvent (String eventargument)
{
"Eventargument" for parameters passed from the client's JavaScript
result = "The content returned from the server side:" + eventargument;
}

Postback callback Result
public string GetCallbackResult ()
{
return result;
}
} writing client Script

Client script is mainly used for information interaction between the server side and the client, take this example, we in the previous page logic code used a named eventargument parameter, this is how to achieve the transfer of parameters? We'll discuss it in later chapters and now add the following JavaScript function code to the page

function CallServer (inputcontrol,context)
{
The callback has not yet processed its preloaded display value at full time
context.innerhtml = "Load ...";
For the information you enter in the text box, and Arg is here to pass its value to the
RaiseCallbackEvent (String eventargument) method corresponds to the eventargument
arg = Inputcontrol.value;
Gets a reference to a client function that, when invoked, initiates a client callback to the server-side event.
<%= Clientscript.getcallbackeventreference (This, "Arg", "receiveserverdata", "context")%>;
}
We refer to a clientscript.getcallbackeventreference (...) in the above JavaScript function code. method, what function does this method achieve? The following is an excerpt from the MSDN2 on Clientscript.getcallbackeventreference (...) Detailed description of.

public string GetCallbackEventReference (Control control,string argument,string clientcallback,string context)

Parameters:

Parameters Role
Control Server control that handles client callbacks. The control must implement the ICallbackEventHandler interface and provide a raisecallbackevent method.
Argument Passes a parameter to the server-side RaiseCallbackEvent method from the client script.
Clientcallback The name of a client event handler that receives the results returned by the server-side event.
Context Client script information at the client before the callback is started. The result of the script is passed back to the client event handler.
return value The name of the client function that invoked the client callback.

The following is an overloaded list of clientscriptmanager.getcallbackeventreference methods

Name Description
Clientscriptmanager.getcallbackeventreference (Control, String, String, String) Gets a reference to a client function that, when invoked, initiates a client callback to the server-side event. The client function for this overloaded method contains the specified control, parameters, client script, and context.
Clientscriptmanager.getcallbackeventreference (Control, String, String, String, Boolean) Gets a reference to a client function that, when invoked, initiates a client callback to the server-side event. The client function for this overloaded method contains the specified controls, parameters, client script, context, and Boolean values.
Clientscriptmanager.getcallbackeventreference (Control, String, String, String, String, Boolean) Gets a reference to a client function that, when invoked, initiates a client callback to the server-side event. The client function for this overloaded method contains the specified control, parameter, client script, context, error handler, and Boolean value.
Clientscriptmanager.getcallbackeventreference (String, String, String, String, String, Boolean) Gets a reference to a client function that, when invoked, initiates a client callback to the server-side event. The client function for this overloaded method contains the specified target, parameter, client script, context, error handler, and Boolean value. We make a systematic description of the entire program, and list the front page code and background logic code, which allows you to have an intuitive understanding of the program.

Background Code CallBackExample.aspx.cs


Code Description:

To successfully run server code from a client without performing a postback, you must implement the appropriate interface in the server page code. To do this we declare the ICallbackEventHandler interface in line 12th of the code. Lines 15th and 19 Create two server-side code callback methods. Where do the "eventargument" string arguments in the "raisecallbackevent ()" Method of line 15th come? To go to line 10th of the foreground page, ARG is equivalent to the argument passed to the RaiseCallbackEvent () method. The "GetCallbackResult ()" method on line 19th returns the results obtained through the "RaiseCallbackEvent ()" method to the client, that is, the result "results" is eventually passed to the 15th code of the foreground page. Receiveserverdata () method, in the "result" argument.

Front Code callbackexample.aspx


Code Description:

To send callbacks and receive results to the server page, we defined 2 client script functions in the foreground page for the two functions. The "CallServer ()" function shown in line 7th implements the function of sending a callback, noting that the function that sent the callback is actually implemented on the server side, because the true implementation of the send callback is the 11th line. Clientscript.getcallbackeventreference () method, and the "callserver ()" function is just for "clientscript.getcallbackeventreference ()" method, and provides some necessary parameters.

Now we're going to detail the implementation details of these client functions, and we'll trigger the OnClick event after clicking the button declared in lines 25th and 26 of the page. When

passes a text box and label as an argument to the corresponding JavaScript function in line 7th after the CallServer (), the "Inputcontrol" and "context" become the text box and label control parameters. The 9th line of code indicates that the "context" will display a "Loading ..." message before the callback result is not accepted until the callback is complete, and the result of the callback is displayed in the context with the code in line 17th. The 10th line of code indicates that the input value of the text box is given "Arg" and that "Arg" is the corresponding 2nd parameter in the Clientscript.getcallbackeventreference () method of line 12th code. The first parameter uses "This" to represent a reference to this page, because the Clientscript.getcallbackeventreference () method is also implemented in callbackexample.aspx. The third parameter represents the client function that accepts the callback result, which matches the Receiveserverdata () function implemented by the 15th line of code (note that the function name must be consistent or cause an error), and the result of the callback will be displayed through "context". The fourth parameter "context" is used for contexts returned from the server side because the Clientscript.getcallbackeventreference () method is executed on the server side where the "context" content originally passed in the method is loaded Information, the callback returns "context" is rewritten in line 17th, and you can set the argument to "null" if there is no reference to it.

  Client callback program that reads database information

This program is a realization read the Northwind database emlpoyees information, for this reason you must first ensure that the Northwind database exists. The following figure is the contents of the Emlpoyees table.


A client callback occurs when the text box enters the user name you want to find, and then clicks the callback button. This is the display result of finding to the user


Display information that does not exist for the user:


Background code: ClientCallbacksSimple.aspx.cs

Using System;
Using System.Data;
Using System.Configuration;
Using System.Collections;
Using System.Web;
Using System.Web.Security;
Modified using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Web.UI.HtmlControls;
Using System.Data.SqlClient;

Public partial class ClientCallbacksSimple:System.Web.UI.Page, 13
System.Web.UI.ICallbackEventHandler
14 {
protected string Struserinfo; Save Read User Information
16//Raise callback Event
-public void RaiseCallbackEvent (string txtfirstname)
18 {
if (txtFirstName!= null)
20 {
SqlConnection conn = new SqlConnection ("Data source=localhost;initial
catalog=northwind;integrated Security=sspi ");
Conn. Open ();

SqlCommand cmd = new SqlCommand ("Select Employeeid,firstname,city,address 25
From Employees where Firstname= @FirstName ", conn);
-CMD. Parameters.Add ("@FirstName", SqlDbType.NVarChar, 10). Value = txtFirstName;
SqlDataReader dr = cmd. ExecuteReader ();

if (Dr. Read ())
29 {
Struserinfo = "Employee code:" + dr["EmployeeID"] + "\ r \ n";
Struserinfo + + "Name:" + dr["FirstName"] + "\ r \ n";
Struserinfo + + + "Residential City:" + dr["urban"] + "\ r \ n";
Struserinfo + = "Address:" + dr["adress"]. ToString (). Replace ("\ r \ n", "") + "\ r \ n";
Struserinfo + = "Server query time:" + DateTime.Now.ToLongTimeString ();
35}
Or else
37 {
if (String.IsNullOrEmpty (txtFirstName))
39 {
Struserinfo = "Please enter your name";
41}
Or else
43 {
Struserinfo = "No person in search";
45}
46}

The cmd. Dispose ();
Dr. Dispose ();
Conn. Dispose ();
50}
51}

52//Return callback result
The public string GetCallbackResult ()
54 {
Struserinfo return; Return basic information about the employee
56}
57}
Code Description: In the RaiseCallbackEvent () method, an input data from the foreground page text box is passed as its parameter, which is the user name to query from the database. The function of the 第28-34 line code is to read the user's details and to save the user information in a string struserinfo. If you do not find the appropriate user, return some error message, see Code 36-45. The GetCallbackResult () method sends back the callback result, which is a string that holds the user information.

Foreground code: clientcallbackssimple.aspx

<%@ Page language= "C #" autoeventwireup= "true" codefile= "ClientCallbacksSimple.aspx.cs"
inherits= "Clientcallbackssimple"%>
<title> Client callback program that reads database information </title>
<script type= "Text/javascript"
Modified function OnCallback (Struserinfo,context)
08 {
Results.innertext = Struserinfo;
10}
One </script>
<body>
<form id= "Form1" runat= "Server" >
<div>
16 Name: <input id= "txtUserName" type= "text"/>
<input id= "btncallback" type= button "value=" Callback "Document.form1.txtUserName.value",
"OnCallback", null)%> "/>
<BR/>
<div id= "Results" style= "Background-color:pink" > </div>
</div>
</form>
</body>
Code Description: The biggest difference between this program and the first program is that there are some nuances on the front page. As shown in code 17-19, the Clientscript.getcallbackeventreference () method of sending the callback is written directly in the Click event of the button, which is also a feasible and straightforward way. The 3 parameters of the Clientscript.getcallbackeventreference () method are "OnCallback", which indicates the oncallback () script function that returns the callback result to the client after the callback completes, This callback result Struserinfo will be displayed as a parameter of the function on the page, as shown in code 9. Since we do not use contextual contact here, the 4 parameters of the Clientscript.getcallbackeventreference () method are "null", but the OnCallback () script function still retains the "context" argument. Because this is a fixed format for the client function that accepts the callback result.

   Summary:

Note that all asynchronous technologies, such as the callback client callbacks discussed in this article, and Microsoft's new Atlas framework, are no longer using traditional postback. Therefore, when the client renders data returned by the server side, the the browser will not see a flashing green status bar, and the asynchronous process only transfer and accept a small amount of data, rather than postback process passed in the entire viewstate state, so the program in the performance of the implementation of a greater increase. Hope that the reader can patiently understand and practice the above two examples, only through their own practice to understand the essence of the client callback.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.