"No refreshing page" is just an inaccurate effect description (in fact, there are other methods to achieve this effect). More specifically, it is said: on the page, use JavaScript to call a method on the server side and then process the returned data. The most standard method to implement it is, of course, XMLHTTP. However, programmers are all lazy people who want to have more convenient methods or better packaging. For example, lostinet's handler is a good packaging for XMLHTTP.
Finally, in ASP. NET 2.0, we can easily achieve this. The server implements system. web. UI. the control of the icallbackeventhandler interface can process the requests and data transmitted from the JS script on the page through the raisecallbackevent () method. After processing, the results are returned to the page. The underlying layer of this capability is still XMLHTTP.
First, let's take a look at how JavaScript calls the method on the server:
<Script language = "javascript" type = "text/javascript">
Function ClientMethod ()
{
// Obtain the Server Control (ControlName is the control name)
Var Control = document. getElementById ("ControlName ");
// ServerMethod is the server method name, and <% = SplitChar %> is a specific character (to avoid the parameter with a delimiter ),
// Control. value is a ServerMethod parameter (that is, the value of the Control)
Var arg = "ServerMethod <% = SplitChar %>" + Control. value;
// Enable client callback for server-side events
<% = Clientscript. getcallbackeventreference (this, "Arg", "result", "") %>;
}
// Process the client callback result
Function result (result)
{
Alert (result );
}
</SCRIPT>
Next let's continue to look at the server method:
// Define a separator first
Public char SplitChar = (char) 14;
First, you must implement the ICallbackEventHandler interface. Public string str_content;
Public void RaiseCallbackEvent (string the_string)
{
Str_content = the_string;
}
Public string GetCallbackResult ()
{
// Split the parameters passed by the client
String [] parts = str_content.Split (SplitChar );
// Generate the parameter queue of ServerMethod
Object [] theArgList = new object [parts. Length-1];
For (int I = 1; I <parts. Length; I ++)
{
TheArgList [I-1] = parts [I];
}
// Call ServerMethod
Return (string) GetType (). GetMethod (parts [0]). Invoke (this, theArgList );
}
// Return the Html code of the specified control
Private string RenderControl (Control control)
{
StringWriter writer = new StringWriter (CultureInfo. InvariantCulture );
HtmlTextWriter Htmlwriter = new HtmlTextWriter (writer );
Control. RenderControl (Htmlwriter );
Htmlwriter. Flush ();
Htmlwriter. Close ();
Return writer. ToString ();
}