Invoke ASP.NET Web service from javascript without proxy





3.00/5 (4 votes)
This sample demonstrates how to call an external Ajax web service without creating code behind proxy from JavaScript
Introduction
Traditionally when we consume a web service, we create a proxy of the by adding a web reference thru Visual studio. This proxy class contains web service exposed methods and these
methods can be invoked from code behind.This works fine if web service path does not change.
Secondly if new functionality is exposed from the web service, we need to change the update the web reference and proxy will be updated accordingly.
At some places where we need to populate data dynamically based on Database driven configuarations like integrating various systems in ERP applications, and if we do code change
in highly configurable environments, the overall efforts would be exceede if we do static code change and further cost of customization would be unexpected high.
We can call an Ajax web service easily by using Sys.Net.WebServiceProxy to invoke the
Web service from Javascript, just we need to add Script Manager in the Page.
Background
Some time back I one of my friend was developing an ERP kind of product where he was populating data based on the Database entries, like if type of the datasource is SP,Table,view or Web service; he was fething the data from the database(s) but calling the Web service he has to depent upon static proxy class created at the time of development.
During the customization of the product he can change only DB entries, aspx and javascript(s).
Using the code
I have created One Ajax web service project and one Web project in VS 2008.
The web service return the current server time and made it Ajax enabled by putting [System.Web.Script.Services.ScriptService] attribute at class level.
I am calling this web service from different project, having one simple form.
On button click I am invoking web service by using Sys.Net.WebServiceProxy class provide by Ajax.
var webServicePath='http://localhost/TimeWebService/TimeService.asmx'; var webMethod='GetServerTime'; Sys.Net.WebServiceProxy.invoke(webServicePath, webMethod, false,{}, OnSucceeded, OnFailed,"User Context",1000000);
function OnSucceeded(result, eventArgs) { var RsltElem = document.getElementById("lblTime"); RsltElem.innerHTML = result; }
I have developed the sample in C# and uploaded the sample in zip format.
History