Calling Web Service Methods Synchronously in ASP.NET AJAX
Update: I had forgot to send the code for the synchronous executor. Here it is, as an attachment.
AJAX, standing for Asynchronous JavaScript and XML, is, well, asynchronous by default. Usually, that is exactly what we want, but there may be times when we want to execute some operation synchronously.
The ASP.NET AJAX (previously known as ASP.NET AJAX Extensions) allows us out of the box to call web service methods asynchronously. See this example:
...<script type="text/javascript">
function onAddSuccess(result, context, functionName)
{
window.alert('Result: ' + result);
}
function onAddFailure(error, context, functionName)
{
window.alert('Error: ' + error);
} </script>...
<asp:ScriptManager ID="ScriptManager" runat="server">
<Services> <asp:ServiceReference Path="~/CalculatorService.asmx" /> </Services> </asp:ScriptManager><
asp:Button runat="server" ID="Button1" OnClientClick="CalculatorService.Add(1, 1, onAddSuccess, onAddFailure, null)" Text="Add 1 + 1" />...
[ScriptService][
WebService(Namespace = "http://tempuri.org/")][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class CalculatorService : WebService{
[ScriptMethod][
WebMethod]public Int32 Add(Int32 a, Int32 b){
return (a + b);}
}
If all goes well, you would get the string "Result: 2" coming from the onAddSuccess callback function.But in some cases, for example, an ASP.NET Custom Validator, you must get an answer immediately. Have a look at the following code:
function ExecuteSynchronously(url, method, args){
var executor = new Sys.Net.XMLHttpSyncExecutor(); // Instantiate a WebRequest.var request = new Sys.Net.WebRequest(); // Set the request URL.request.set_url(url + '/' + method); // Set the request verb.request.set_httpVerb('POST'); // Set request header.request.get_headers()['Content-Type'] = 'application/json; charset=utf-8'; // Set the executor.request.set_executor(executor);
// Serialize argumente into a JSON string.request.set_body(Sys.Serialization.JavaScriptSerializer.serialize(args));
// Execute the request.request.invoke();
if (executor.get_responseAvailable()){
return (executor.get_object());}
return (false);}
function add(){
var result = ExecuteSynchronously('CalculatorService.asmx', 'Add', { a: 1, b: 2 });window.alert('Result: ' + result);}
<
asp:Button runat="server" ID="Button1" OnClientClick="add()" Text="Add 1 + 1" />You get the result immediately in the add method.