AJAX Web Services
Connecting to web services in AJAX is really easy. To setup a web service that can be called on the client, simply do the following. Create a web service in Visual Studio; add one to the web project by right-clicking on the desired folder and selecting the new item option. Select the web service option, which creates an ASMX. This is the extension for a service in the web project.
Add the following attribute: [System.Web.Scripts.Service.ScriptService] When the project runs, a client proxy is generated automatically for you, one that matches your namespace/class name. If you create a service in namespace Mains.Examples, with a service name of ArticleCodeGenerator, the following can be run on the client without having to write any code:
<script language="javascript">
function pageLoad()
{
Mains.Examples.ArticleCodeGenerator.GenerateOutline(onSuccess, onFailure, $get('<%= lblTemplate.ClientID %>'));
}
function onSuccess(results, userContext, methodName)
{
//called when successful call to service
//results equals the object returned from the service
//userContext is the reference to the label
}
function onFailure(results, userContext, methodName)
{
//called when failure occurs
}
</script>
<asp:Label id="lblTemplate" runat="server" />
The way the service method is setup is illustrated in the following:
ServiceMethod( <any parameters separated by commas>, <success callback>, <failed callback>, <context>);
The success or failed callback has to meet the template shown above; results contains a reference to the object returned from the method. If an actual object and not a primitive type, the object is converted using JSON. The context object can in reality be anything, and is often passed a value to the UI control (as shown in many examples).
Add a reference to the service to the script manager:
<asp:ScriptManager ...>
<Services>
<asp:ScriptReference Path="..path to ASMX" />
</Services>
</asp:ScriptManager>
That's how easy it is to include web services into AJAX. Even cooler is how Visual Studio provides intellisense for this object.