"No refreshing page" is just an inaccurate effect description (in fact, there are other methods to achieve this effect). More specifically, it is said:Call a method on the server using JavaScript on the page and 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.
The following is a simple demonstration:
On the page, we put two text boxes and a button:
<Input id = "txtmessage">
<Input onclick = "calltoserver ();" type = "button" value = "call to server">
Result: <input id = "txtresult">
When you click the button, the JS script method calltoserver () will be called. The JS script is as follows:
Function calltoserver ()
{
VaR Param = Document. getelementbyid ("txtusername"). value;
VaR context = "";
<% = Clientscript %>
}
Function handleresultfromserver (result, context)
{
Document. getelementbyid ("txtresult"). value = result;
}
The handleresultfromserver () method writes the data returned from the server to the txtresult text box.
Let's look at the server code:
Public partial class default_aspx: system. Web. UI. icallbackeventhandler
{
Private string clientscript
{
Get
{
Return this. getcallbackeventreference (this, "Param", "handleresultfromserver", "context ");
}
}
Public String raisecallbackevent (string eventargument)
{
Return "the client sends [" + datetime. Now. tostring () + "] to [" + eventargument + "].";
}
}
We let the page directly implement the icallbackeventhandler interface, and then return the server time and transmitted data together in the raisecallbackevent () method defined by the interface.
The clientscript attribute is used to call the getcallbackeventreference () method of the page, obtain the JS script that enables the client to call the method of the server, and output it to the calltoserver () method of the page, in this way, when you click the page button, the page will start executing the calltoserver () method that calls the server method.
Note the parameters of the getcallbackeventreference () method. In the parameters, we define which variable of the client contains the information such as the method to be passed to the server and the method to call the client after the server method is executed. For details about getcallbackeventreference (), see here.
Finally, the execution result of this page is: