ARTICLE :
 

Asynchronously calling .NET webservice from client side JavaScript using ASP.NET AJAX

by SBajra on August 1st, 2011

Introduction

This article demonstrates how to make webservice calls from client side JavaScript using ASP.NET AJAX framework.

Background

There are lots of instances when we would need to make asynchronous server-side webservice call from client side JavaScript. This article covers very simple approach on how to make webservice calls using client side Javascript with Microsoft ASP.NET AJAX framework.

Detail

ASP.NET AJAX functionality is built-in .NET framework with the release of .NET 3.5. If you are using .NET framework 2.0, you would need to install AJAX extension for .NET 2.0. For this demo, I am using .NET framework 4.0 and Visual Studio 2010.

First of all, let's create an ASP.NET application using Visual Studio. For this demo, I created empty ASP.NET web site.

Now, let's add a .NET ASMX webservice page. For this example, let's add MyService.asmx to the web site. Then let's add a simple webmethod in the codebehind page for webservice.

[WebMethod]
public string Add(int number1, int number2) {
    return (number1 + number2).ToString();
}


Now, we have our sample webservice in our ASP.NET web site. Let's add an ASP.NET page with Javascript to invoke the webservice just created. Let's leave the default filename of ASP.NET page as default.aspx.

In default.aspx page, let's add few lines of code to reference the webservice.asmx we just created. To reference the webservice for client side usage, we will need to use <asp:ScriptManager> control which is part of ASP.NET AJAX framework.
<asp:ScriptManager ID="scriptManager" runat="server">
    <Services>
        <asp:ServiceReference Path="~/WebService.asmx" />
    </Services>
</asp:ScriptManager>

When we add reference to webservice using ASP.NET AJAX framework <asp:ScriptManager> control, ASP.NET AJAX framework will create the JavaScript class on the fly to be used from client side JavaScript.

Now, we can invoke the webservice from Javascript directly.
<script language="javascript" type="text/javascript">
	WebService.Add(3, 5, onSuccessEvent);

	function onSuccessEvent(result) {
		alert(result);
	}
</script>

In this way, we can easily make any webservice call using ASP.NET AJAX framework and Javascript.

Conclusion

By using ASP.NET AJAX framework that comes with .NET framework, we can easily create client side reference to the webservice and invoke server side webservice from client side JavaScript.

Download

Click here to download source code

Author:

Profile Photo
SBajra
Date: August 1st, 2011

Comments: