Sunteți pe pagina 1din 5

How to call a Web Service from client-side JavaScript using ASP.

Net AJAX
Published 18.08.2007. Last updated 09.09.2007
Introduction
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 then
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 ASP.Net AJAX technology in general and
ASP.Net AJAX enabled Web Services in particular.
Background
For 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. ASP.Net AJAX technology has shown to be 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
Whell, 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 was using ASP.Net AJAX version 1.0 while writing this article.
Creating AJAX enabled Web Service
Lets us assume that you managed to install the ASP.Net AJAX framework. So we
can start with creating new AJAX ebabled Web Application:

What we need now is the AJAX enabled Web Service. Let us add 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 ASP.Net Application
ASP.Net applications web.config file also has to be modified in order to enable Web
Service calls from client-side JavaScript code.
This modification is though made for you by Microsoft Visual Studio 2005 if you are
using ASP.Net AJAX template. Here is the example of what can be inserted into
httpHandles 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 Script Manager object on your page:
<body>

<form id="form1" runat="server">


<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp: ScriptManager>
<div>
</div>
</form>
</body>
Then we have to add Services collection to our ScriptManager object, add
ServiceReference to the Services collection and specify 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, button to trigger Web Service request and
a text box to provide the input for the Web Service:
SendRequest - this function will send asyncroneus request to the Web
Service
OnComplete - this function will receive result from the Web Service

OnError - this function will be triggered if an error occures while executing


Web Service

OnTimeOut - this function will be triggered if Web Service will not respond

MyTextBox - text box with the input for the Web Service

RequestButton - the button that triggers SendRequest function

The result might look like this:


<head id="Head1" 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
server-side Web Service and treats returned response:

If we supply 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 client-side JavaScript
code invokes Web Service methods provides us with a lot of flexibility to extend the
web site 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.

S-ar putea să vă placă și