Introduction
The ASP.NET AJAX framework provides us with an easy and elegant way to consume Web Services from client-side JavaScript code. In fact, it is even easier to write a simple AJAX enabled Web Service and connect to it from client-side JavaScript than it is to write an article like this one. In this article, I have tried to collect some of my experiences which I hope can be useful for you to get started with using the ASP.NET AJAX technology in general and ASP.NET AJAX enabled Web Services in particular.
Background
Some time ago, I was looking for a possibility to dynamically update some parts of my page without refreshing the rest of it. In fact, I only needed to update some small text fields on my page. Apart from this text, my page had a lot of graphics on it, and it was a bit irritating for users to watch the whole page flashing while those text fields were updated. So, I had to avoid refreshing the graphics on the page while updating my text data. The ASP.NET AJAX technology has shown to be the perfect choice for this purpose. It is possible to use different AJAX techniques to achieve this kind of behaviour, for example: partial page updates, page methods, and Web Service calls. In this article, I will try to cover the Web Service approach.
Installing ASP.NET AJAX
Well, first of all, to get started, you will have to install the ASP.NET AJAX framework. You can do the first step by visiting AJAX: The Official Microsoft ASP.NET 2.0 Site. There, you can find links and pretty good instructions on how to install and get started with ASP.NET AJAX. I am using ASP.NET AJAX version 1.0 while writing this article.
Creating an AJAX Enabled Web Service
Let us assume that you managed to install the ASP.NET AJAX framework. We can now start with creating a new AJAX enabled Web application:
What we need now is the AJAX enabled Web Service. Let us add a new Web Service called MySampleService to the project:
In order to AJAX enable it, we will have to add the following attribute to the Web Service declaration part:
[System.Web.Script.Services.ScriptService()]
When this is done, our Web Service is ready to respond to client-side JavaScript calls. One more thing has to be done here: we need the Web Method that we will call from client-side JavaScript. Let us define it like this:
[WebMethod]
public string GetServerResponse(string callerName)
{
if(callerName== string.Empty)
throw new Exception("Web Service Exception: invalid argument");
return string.Format("Service responded to {0} at {1}",
callerName, DateTime.Now.ToString());
}
Configuring the ASP.NET Application
The ASP.NET application's web.config file also has to be modified in order to enable Web Service calls from client-side JavaScript code.
This modification is made for you by Microsoft Visual Studio 2005 if you are using the ASP.NET AJAX template. Here is an example of what can be inserted into the httpHandlers
section of your web.config file:
<configuration>
...
<system.web>
...
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false"
type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=1.0.61025.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
...
</httpHandlers>
...
</system.web>
...
<configuration>
Making Client-side JavaScript Code
Let us take a look at the default.aspx file that was automatically created in our project (if it was not - then you will have to add one manually). First, we have to make sure that we have one and only one instance of the ScriptManager
object on our page:
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div></div>
</form>
</body>
Then, we have to add a Services
collection to our ScriptManager
object, add a ServiceReference
to the Services
collection, and specify the Path
to the desired service. The result might look like this:
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WebServices/MySampleService.asmx" />
</Services>
</asp:ScriptManager>
<div></div>
</form>
</body>
or like this, if you prefer to do it directly in your code-behind file:
ScriptManager1.Services.Add(new ServiceReference("~/WebServices/MyWebService.asmx"));
Now, we need some client-side functions, a button to trigger the Web Service request, and a text box to provide the input for the Web Service:
SendRequest
- this function will send an asynchronous request to the Web ServiceOnComplete
- this function will receive the result from the Web ServiceOnError
- this function will be triggered if an error occurs while executing the Web ServiceOnTimeOut
- this function will be triggered if the Web Service will not respondMyTextBox
- the ext box with the input for the Web ServiceRequestButton
- the button that triggers the SendRequest
function
The result might look like this:
<head runat="server">
<title>Web Service call from client-side JavaScript</title>
<script language="javascript" type="text/javascript">
function SendRequest()
{
MySampleService.GetServerResponse(form1.MyTextBox.value, OnComplete, OnError,
OnTimeOut);
}
function OnComplete(arg)
{
alert(arg);
}
function OnTimeOut(arg)
{
alert("timeOut has occured");
}
function OnError(arg)
{
alert("error has occured: " + arg._message);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WebServices/MySampleService.asmx" />
</Services>
</asp:ScriptManager>
<div>
<input type="text" value="" id="MyTextBox" />
<input type="button" value="Send Request to the Web Service"
id="RequestButton" onclick="return SendRequest()" />
</div>
</form>
</body>
This is basically it. You have a functioning client-side JavaScript code that calls a server-side Web Service and treats the returned response. If we supply an empty input value to the GetServerResponse
method of MySampleService
, then as expected, it will throw an exception. This exception will be caught by the OnError
function in the client-side JavaScript:
Conclusion
The described client-to-server communication model where the client-side JavaScript code invokes the Web Service methods provides us with a lot of flexibility to extend our website functionality. At the same time, the traffic is minimal: we send only the input data required by the Web Method, and we receive only the return value from the method being invoked.
History
You can always find the most up-to-date version of this article in the AJAX section of my website.