Friday, June 15, 2007

Consuming Web Service from Client-Side code

We can consume web service from the client side using web service behaviour.The WebService behavior enables client-side script to invoke remote methods exposed by Web Services, or other Web servers, that support the SOAP and Web Services Description Language (WSDL) 1.1. This behavior provides developers the opportunity to use and leverage SOAP, without requiring expert knowledge of its implementation. The WebService behavior supports the use of a wide variety of data types, including intrinsic SOAP data types, arrays, objects, and XML data.
The WebService behavior is implemented with an HTML Component (HTC) file as an attached behavior, so it can be used in Microsoft Internet Explorer 5 and later versions.

WebService HTC File (webservice.htc)
The WebService behavior is encapsulated in an HTC file. Therefore, before you begin using the behavior in your own Web pages, download the WebService HTC File from the following location and copy it to a folder in your Web project.
http://msdn.microsoft.com/archive/default.asp?url=/archive/en-us/samples/internet/behaviors/library/webservice/default.asp

Now suppose you want to consume web service from "http://localhost/MathsWebService/MathsService.asmx" location whose web method "Sum" that takes 2 integer values and returns integer sum, you want to call from the client side code.
Example-

< body onload="init()" >
< form id="form1" runat="server" >
< div id="service" style="behavior: url(webservice.htc)" >
< /div >
Num 1:< asp:TextBox ID="n1" runat="server" > < /asp:TextBox >< br />
Num 2:< asp:TextBox ID="n2" runat="server" > < /asp:TextBox >< br />
< asp:Button ID="btnsum" runat="server" OnClientClick="return fnSum()" Text="Sum" />
< /form >
< /body >

Note:We have added web service behaviour in our web page using style attribute.

< script language="JavaScript" >

function init()
{
service.useService("http://localhost/MathsWebService/MathsService.asmx?WSDL","MyMath");
}
function fnSum()
{
var intA = document.getElementById('n1');
var intB = document.getElementById('n2');
service.MyMath.callService(Mycallback,"Sum", intA.value, intB.value);
return false;
}
function Mycallback(result)
{
alert("Result = " + result.value);
}
< /script >

Note: webservice.htc file contains useService and callService methods.

This example will take 2 integer values from the textboxes and user click on Sum button the result will be displayed in the alert message.

Reference:
http://msdn2.microsoft.com/en-us/library/ms531032.aspx

No comments: