. Net built-in Ajax Working Principle

Source: Internet
Author: User
You can use the clientscriptmanager class to call the client callback (callback) when you want to run the server code from the client without executing the PostBack operation ). This is called an out-of-band callback to the server. In the client callback, the ASP. NET web page of the client script function sends an asynchronous request. Modify the normal lifecycle of a webpage to process callback.

The callback process is as follows: (1) the client sends a request, which includes specifying the update control and passing parameters. (2) Server Response and processing. (3) The server returns the processed content as a string. (4) The client specifies a function to accept the return value. (5) The client updates the specified control. Perform the following steps to Use callback: (1) Implement the icallbackeventhandler interface in the control or page class. This interface has two methods: raisecallbackevent and getcallbackresult. The raisecallbackevent method is the callback execution method that processes the callback content. It does not return values, but 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. Next, the getcallbackresult method is triggered. It returns the result to the client script. (2) generate a client script that calls the callback. The clientscriptmanager class can be used to generate the getcallbackeventreference method. (3) Compile the client script generated in the Code call (2. The following example shows the callback process... Create an ASP. NET application and set the default form interface as follows: 1. Implement the icallbackeventhandler interface in the defalut. aspx. CS class. The Code is as follows: Public partial class _ default: system. Web. UI. Page, icallbackeventhandler
{
String callbackresult;

# Region icallbackeventhandler Member

// This is triggered after the raisecallbackevent method is triggered. It returns the result to the client.
// The result in the oncallbackcomplete (result, context) method of the client script is actually the callbackresult
Public String getcallbackresult ()
{
Return callbackresult;
}

// The callback execution method is triggered first. A parameter in it accepts the value "1111111" from the client
Public void raisecallbackevent (string eventargument)
{
Try
{
Callbackresult = WebService. getresult (eventargument); // because the getresult method of WebService is called, you can also put the getresult method here.
}
Catch (exception E)
{
Trace. Write (E. Message );
Throw new exception ("Call failed ");
}
}

# Endregion
} 2. Generate the client script that calls the callback. Add the following code to the page_load event of the default class: Public partial class _ default: system. Web. UI. Page, icallbackeventhandler
{
Protected void page_load (Object sender, eventargs E)
{
If (iscallback)
{
Return;
}

// Return the actual callback script according to the input parameters

// The Name Of The Server Control whose target 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 server
// Clientcallback the name of a client event handler. the handler receives the result of a successful server event.
// The client script calculated on the client before the context starts the callback. The result of the script is returned to the client event handler.
// Name of the clienterrorcallback client event handler. the handler receives the result when an error occurs in the server event handler.
// Useasynctrue indicates synchronous execution callback; false indicates asynchronous execution callback.
String callbackfunctioncall = clientscript. getcallbackeventreference (this, "gettextvalue ()", "oncallbackcomplete", null, "oncallbackerror", true );

// Register the client script
String csname = "Callback"; // The Key of the client script to be registered.
If (! Clientscript. isclientscriptblockregistered (GetType (), csname ))
{
// Type the type of the client script to be registered.
// Key of the client script to be registered.
// The client script Text to be registered by the script.
// Addscripttags indicates whether to add a Boolean value of the script flag.
Clientscript. registerclientscriptblock (GetType (), csname, "function doclientcallback () {" + callbackfunctioncall + "}", true );
}
}
} 3. Write the client code and add the following Javascript script to the default. aspx file: <SCRIPT type = "text/JavaScript">
Function gettextvalue () // parameter to be passed to the server
{
VaR arg1 = Document. getelementbyid ("text1"). value;
VaR arg2 = Document. getelementbyid ("text2"). value;
VaR Arg = "arga =" + arg1 + "& argb =" + arg2; // note the transfer method here.
Return ARG;
}

Function oncallbackcomplete (result, context) // callback successful
{
// Alert (result );
Document. getelementbyid ("textarea1"). value = result;
}

Function oncallbackerror () // callback failed
{
Alert ("Callback failed! ");
}
</SCRIPT> Add the getresult method of the WebService class called in the raisecallbackevent method in (1), and add a Web Service Page named WebService. asmx to the project. In WebService. asmx. the CS file defines a method named getresult. This code can also be directly placed in the raisecallbackevent method. However, to achieve the effect of WebService calling, it is still placed in a WebService file separately, the Code is as follows: Public class WebService: system. Web. Services. WebService
{

[Webmethod]
Public static string getresult (string name) // wait for the function
{
String [] keyvaluepairs; // array containing "="
String [] keyValue; // only an array of strings
Namevaluecollection m_querystring = new namevaluecollection (); // a set of key-value pairs

Keyvaluepairs = Name. Split ("&". tochararray ());
If (keyvaluepairs. length> 0) // If the passed parameter is arga = arg1 & argb = arg2 ...... Format, that is, more than one parameter
{
For (INT I = 0; I <keyvaluepairs. length; I ++)
{
KeyValue = keyvaluepairs. getvalue (I). tostring (). Split ("=". tochararray ());
M_querystring.add (keyValue [0], keyValue [1]);
}
}
Else // only one passed Parameter
{
KeyValue = Name. Split ("=". tochararray ());
If (keyValue. length> 0) // If a parameter is passed
{
M_querystring.add (keyValue [0], keyValue [1]);
}
}
// Call the parameter value through htquerystring ["arga "].
Return "the first parameter is:" + m_querystring ["arga"]. tostring () + "\ n the second parameter is:" + m_querystring ["argb"]. tostring ();
}
} The execution result is as follows: the user interaction of the page is the same as that of the three pages opened by Ajax in the previous blog, but the code is greatly reduced, because we do not need to write code to parse XML or process XMLHttpRequest objects.

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.