First you construct a simple user interface to facilitate this:
This HTML document simply contains two text fields that accept the integer arguments and a button to calculate
the result of the addition of the two arguments. The button contains an onclick handler, which
points to a JavaScript function. This function will execute your asynchronous call to your web service.
Next, have a look at the code of your web service, which is extremely simple and should be very familiar
to all developers who have created web services. The web service itself was created using the endpoint
of AsyncService.asmx and contains a method, more specifically a WebMethod, called Adder:
using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
///
/// Summary description for AsyncService
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class AsyncService : System.Web.Services.WebService {
public AsyncService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
[WebMethod]
public int Adder(int arg1, int arg2)
{
return arg1 + arg2;
}
}
Finally, examine the client-side code to call the web service shown previously:
function ExecWebService()
{
if (xmlHttpObj)
{
var disp = document.getElementById("spnDetailDisplay");
var ctlVal1 = document.getElementById("val1");
var ctlVal2 = document.getElementById("val2");
// We want this request synchronous
xmlHttpObj.open("POST","http://" + location.host +"/Test/AsyncService.asmx/Adder", true);
xmlHttpObj.onreadystatechange = function()
{
if (xmlHttpObj.readyState == 4)
{
// If the request was ok (ie equal to a Http Status code of 200)
if (xmlHttpObj.status == 200)
{
var xmlDoc = xmlHttpObj.responseXML;
var result = xmlDoc.lastChild.childNodes[0].nodeValue;
disp.childNodes[0].nodeValue = "Result: " + result;
}
else
{
var fault = xmlHttpObj.responseText;
alert("Error Occurred! \n\n" + fault);
}
}
}
// Execute the request
xmlHttpObj.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpObj.send("arg1=" + ctlVal1.value + "&arg2=" + ctlVal2.value);
}
}
No comments:
Post a Comment