Ajax and the ASP. NET 2.0 callback framework (English version)

Source: Internet
Author: User
Tags string back
Interaction with a web application can be initiated via a synchronous page PostBack or an out-of-band PostBack, known as a client callback, from the client to the server. the default ASP. net web page model uses synchronous page postbacks, which are usually triggered on the client by submitting an HTML form. during a page PostBack, the web page and controls are recreated and a new version of the entire web page is rendered on the client. in addition, most of the application logic is present on the server-side. unfortunately page postbacks often introduce a great deal of processing overhead which can decrease performance. since the entire page must be reconstructed via a synchronous request to the server, the client must wait for a response to continue working. on the other hand, client callbacks can improve performance and enhance the end user experience when working with a web application. callbacks utilize a set of technology standards commonly referred to as Ajax (Asynchronous JavaScript and XML ).

Ajax uplodes:

  • Presentation content using XHTML and CSS
  • Dynamic Display and interaction with XHTML (DHTML) using the Document Object Model (DOM)
  • Data Interchange Using strings, often in XML format
  • Asynchronous Data Retrieval Using an HTTP request object
  • Javascript-to bind everything together

Client callbacks can be synchronous or asynchronous. in either case, the browser creates a new connection to send the callback to a remote server, thus the callback is out-of-band. the contents of the entire page do not need to be submitted, so the page lifecycle for a callback skips events associated with rendering page contents on the server. in addition, sending an asynchronous callback to a server permits an end user to continue working in the client application while the request is processed. when the response is returned, the appropriate content in the web page is updated without refreshing the entire page. the diagrams below state the difference between synchronous and asynchronous communication between a client application and a server.

Synchronous

Asynchronous

The ASP. NET 2.0 implementation of client callbacks uses the client callback manager to provide an extensible callback framework. after initial Page load, subsequent requests to server-side code are made by a client-side component, without refreshing the entire web page. the page runs a modified version of its normal life cycle (see dimo-below) where the page is initiated and loaded, but the page contents are not rendered. instead, a special method in the server-side code is invoked, which processes the callback request content, then returns a value to the browser that can be read by JavaScript function. the JavaScript function uses technology inherent to the browser (e.g. dom, DHTML) to update web page content dynamically. the web page continues to stay live while the request is being processed.

The distribelow parameter strates the difference between the page lifecycle sequence of events between a synchronous page PostBack and a client callback. the page. ispostback property will return true for both request types. the page. iscallback property will return true only when the request is a client callback.

Developing an ASP. NET 2.0 page that uses client Callbacks is a two-step process. first, create the server-side code that will be invoked by the client. second, create the client-side code to invoke the callback request and process the response. note that the message in the callback request and response is always a string. the content and format of the string is up to the developer. the request usually provided des a string to tell the server which action to perform and some user provided data. the response usually contains content to be rendered on the client or a set of data to trigger further actions.

Working with callbacks in an ASP. NET web application

The following outline highlights the basic steps used to implement client callbacks in an ASP. NET 2.0 web page. in this example, the current time on the Web server is returned and rendered in the client browser:

  1. Implement the system. Web. UI. icallbackeventhandler.

    The icallbackeventhandler interface can be implemented on a page or a web control. the Interface contains two key methods: raisecallbackevent (string eventargs) and getcallbackresult (). raisecallbackevent () Events es the message in the callback request sent from the client. it can be designed to parse the message and determine what server-side logic will be executed. once the server-side code is finished, it creates a string of values to be sent to the client using the getcallbackresult () method. here is an implementation example of both methods in the code-behind page default. aspx. CS. the eventargument will be updated via a callback request from the client. this is discussed in greater detail below.

    [C #]
    public partial class Default : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler{string returnstring;string ICallbackEventHandler.GetCallbackResult(){return returnstring;}void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument){if (eventArgument == "getservertime"){returnstring = DateTime.Now.ToString();}}
  2. Call the getcallbackeventreference method on the page class.

    The getcallbackeventreference method creates a javascript string in the client web page to start the callback. The usage and method parameters are listed below:

    Usage: GetCallbackEventReference(control, argument, clientCallback, context, clientErrorCallback, useAsync);
    Parameter Name Description
    Control The control or the page which implements icallbackeventhandler.
    Argument Name of a client-side JavaScript variable. references the string sent to the raisecallbackevent method via the eventargument parameter.
    Clientcallback Name of the client-side JavaScript function which will receive the result of a successful server event.
    Context Name of a client-side JavaScript variable. usually used to determine the content of the message (argument) in the callback request. the value of the variable will be stored on the client as the context parameter associated with a callback.
    Clienterrorcallback Name of the client-side JavaScript function which will receive the callback result when an error occurs.
    Useasync Boolean to determine whether a synchronous or asynchronous callback is made to the server.

     

     

     

     

     

     

     

     

     

     

     

     

     

     

    Here is an example of the method used in code. The scallbackfunctioninvocation member variable is a Public String, global to the page class:

    [C #]

     

    Public String scallbackfunctioninvocation;

    Protected void page_load (Object sender, eventargs E)
    {
    Scallbackfunctioninvocation = page. clientscript. getcallbackeventreference (this,
    "Message", "processmyresult", "context", "processmyerror", true );
    }
    At runtime, when the web page is first loaded, the getcallbackeventreference method generates a javascript string that contains the webform_docallback function with the parameters listed above. the next step will discuss adding a reference to this function in client-side code.

  3. Create the client-side code to trigger the callback and process the response.

    Implementing System. Web. UI. icallbackeventhandler and calling getcallbackeventreference will add something similar to the following script tag in your ASPX page at runtime:

    <script src="/WebAppName/WebResource.axd?d=TqQApA1CcEIyShhLjzTczw2&t=632657807109074470" type="text/javascript"></script>

    Webresource. axd is a new HTTP handler in ASP.. NET 2.0 that enables web page and Web Control developers to download resources that are embedded in an assembly. the system. web. dll contains a javascript resource that contains the webform_docallback function. the format of this URL is webresource. axd? D =Encrypted identifier& T =Time stamp Value. The "D" refers to the requested web resource and is an encrypted string of the Assembly name and Resource Name. the "T" is the timestamp for the requested assembly, which can help in determining if there have been any changes to the resource. at runtime, the Javascript resource is downloaded to the client.

    In response cases, Callbacks within a browser are managed using the XMLHTTPRequest object. more specifically, the ASP. NET 2.0 callback framework between des javascript content to support callbacks. the JavaScript function which initiates and manages callbacks in the client browser is webform_docallback. it creates an ActiveX object, Microsoft. XMLHTTP for Internet Explorer browsers or a native XMLHTTPRequest object for other browsers to manage HTTP Communication with a web application on the server. the Microsoft. XMLHTTP object is packaged with the Microsoft XML Document Object Model, part of the MSXML set of components.

    The following code provides an example of the HTML content in An ASPX page configured to work with callbacks. the edits to the code involve two steps:

    1. Add an HTML element and a JavaScript function to create a callback request. in the HTML code below, the click event of an HTML button triggers a call to the JavaScript function getservertime, which in turn callwebform_docallback. the message variable is set to 'getservertime' which is used by the server to determine which action to execute. the server variable <% = scallbackfunctioninvocation %> is translatedWebform_docallback ('_ page', message, processmyresult, context, postmyerror, true)At runtime.
    2. Add two JavaScript Functions to process the callback response and update the page. the processmyresult function takes the callback response string and updates the text content of a div tag in the HTML page. note, this happens dynamically so other objects in the page are not redrawn. the postmyerror function has es the callback message if an error was thrown on the server. in this case, it pops up an alert box.

    The following distriillustrates a callback event at runtime. The green circles indicate the order in which events occur to initiate and process the callback. A short description for each event is provided below:

 

  1. 1. After the web page loads, The onclick event of an HTML button is triggered which callthe User-Defined getservertime JavaScript function.

    2. The getservertime function sets the message and context variables to be sent to the server and callthe ASP. NET 2.0 defined webform_docallback function to create and send the callback request.

    3. A new XMLHTTPRequest object is created to send and receive the asynchronous call to \ from the server.

    4. the XMLHTTPRequest object posts the HTTP request to the server containing the message. on the server, the raisecallbackresult method parses the argument (Message) and executes some business logic-in this case, it converts the time on the server to a string. the getcallbackresult method passes this string back to the XMLHTTPRequest object waiting on the client.

    5. the ASP. NET 2.0 webresource for callbacks directs the callback response string to the registered callback response function, the User-Defined processmyresult function.

    6. the processmyresult function uses the content of the callback response string to dynamically update HTML in the web page. in this case, it inserts HTML into an existing <div> tag to display the server time.

 

 

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.