By default, Microsoft ASP.NET 2.0 AJAX Extensions
applications cannot call Web services unless explicitly enabled, as explained
below...
1) In the
---<system.web>
------<httphandlers>
---------<remove path="*.asmx" verb="*">
---------<add type="" path="*.asmx" verb="*">Microsoft.Web.Script.Services.ScriptHandlerFactory" validate="false"/>
------</httphandlers>
---<system.web>
When the proxy class is generated, the proxy class will expose a JavaScript function for each method in the Web service that has been marked with the WebMethod attribute.
2) In the ScriptManager control on the page, define the Web service location by creating an <asp:servicereference> child element and setting its path attribute.
<asp:ScriptManager runat="server" ID="scriptManager">
<services> <asp:servicereference path="~/WebServices/SimpleWebService.asmx" /> </services></asp:ScriptManager>
This setting instructs ASP.NET 2.0 AJAX Extensions where the service is for which to generate a JavaScript proxy.
You can inspect the generated script for the proxy class by entering the following string in the browser address box http://localhost/myService.asmx/js
Setting up the WebService
The web service must be an asmx file and must contain the [ScriptService] attribute . In the sample above we create a webservice file called SimpleWebService.asmx and it will contain the following code...
---[ScriptService]
---public class SimpleWebService : System.Web.Services.WebService{
------[WebMethod]
------public string EchoInput(String input) {
--------- // Method code goes here.
------}
---}
Calling the WebService from JavaScript
sample 1:
function GetNoReturn(){ Samples.AspNet.CallWebService.GetServerTime();}
sample 2:
function GetTime(){
----Samples.AspNet.CallWebService.GetServerTime(OnRequestComplete);
}
function OnRequestComplete(result){
----// Display the result.
----var RsltElem = document.getElementById("Results");
----RsltElem.innerHTML = result;
}
Sample 3:
function Add(a, b){ Samples.AspNet.CallWebService.Add(a, b, OnRequestComplete);}
Client side Error Handling from
function Div(a, b){ Samples.AspNet.CallWebService.Div(a, b, OnRequestComplete, OnRequestFailure);}
function OnRequestFailure(error){
----// Display the error.
----var RsltElem = document.getElementById("Results");
----RsltElem.innerHTML = "Error on the sever: " + error.get_message();
}
For other scenarios see the following link for a more uptodate set of supported scenarios webserviceProxy
Lead by example
The best example explaining all the above can be found here
No comments:
Post a Comment