Calling ASMX web services directly from javascript
Follow the steps below to get things up and running.
This example assumes you have ASP.NET Ajax and de Web Applications already installed.
1. Create a new project of type "ASP.NET AJAX-Enabled Web Application"
This will create a new Web Application with a Default.aspx that already has a script manager on in, and a preconfigured web.config. Call this project WebServiceDemo
2. Add a web service
Right-click on your web application, click Add/New Item and then Web Service. Call this web service "DemoService".
3. Make a web service callable from script
Open code file "Default.aspx.cs". Notice your class "DemoService" sits in a namespace "WebServiceDemo". You will need this knowlegde later.
Add to the top:
using System.Web.Script.Services;decorate the class with the attribute [ScriptService] and modify the standard hello world method so it looks like this:
[WebService(Namespace = "http://tempuri.org/")]4. Register the service on the page where you want to call it from
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[ScriptService]
public class DemoService : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld( string ToSomeone )
{
return "Hello World" + ToSomeone;
}
}
Open Default.aspx in design view and select the ScriptManager1
Select the "Services" property, and click the button that appears
Click "Add", and enter "DemoService.asmx" for the path property
Click OK. The result should look like this:
<asp:ScriptManager ID="ScriptManager1" runat="server" > <Services> <asp:ServiceReference Path="DemoService.asmx" /> </Services> </asp:ScriptManager>5. Create a client side script to perform the call
Open Default.aspx in source view and enter just before the <head> tag the following code:
<script type="text/javascript">6. Create a button to start the web service calling function
function CallService()
{
WebServiceDemo.DemoService.HelloWorld( "Yourself",
Callback );
}
function Callback( result )
{
var outDiv = document.getElementById("outputDiv");
outDiv.innerText = result;
}
</script>
Drag a button onto the form
Set the property "OnClientClick" to "CallService();return false;"
7. Create div for the output data
Drag a div (from the HTML tab) onto the form.
Set its id to "outputDiv";
If you did everything correctly, the text "Hello World Yourself" should appear beneath your button, without a visible postback.
Notice the following things:
- You always need the fully qualified name of the class to call the webservice: WebServiceDemo.DemoService.HelloWorld
- Calling a webservice from javascript always needs two methods: one to make the actual call, and one to receive the results
- The callback method is added as an extra parameter to the web service method parameters. In C#, the method has one parameter, so in javascript two.
Complete code downloadable here.