Lets move step by step to get a complete hold on this.
Create an AJAX enabled website
Create an AJAX Enabled web site for this
example. Ajax enabled website is same as normal .net website but having few
more additional tags in web.config.
Add Webservice and Javascript
Add a webservice (MyService.asmx) to the
project. Also add a JS file (Jscript.js) to do the client side activities.
Basically we are going to call the Webmethods present in the websevice through
java script.
Add ScriptManager
Add a ScriptManager to the MasterPage with tags as
shown below.
Listing 1
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Scripts>
<asp:ScriptReference Path="JScript.js" />
</Scripts>
<Services>
<asp:ServiceReference Path="MyService.asmx" InlineScript="true" />
</Services>
</asp:ScriptManager>
Do necessary changes to the webservice
You need to add the ScriptService
attribute to the webservice class. Then add your own webmethod. Here we
have added a GetServerTime() method.
Listing 2
[WebMethod]
public string GetServerTime()
{
return DateTime.Now.ToString();
}
Test the Webservice, see if it generates the client
proxy
After this you should
be able to test whether your webservice is ready to receive calls from the
javascript. Basically the webservice URL followed with “/js” or “/jsdebug” will
allow you to download the resulting client proxy. This is possible because of
the presence of Scriptservice Attribute for Webservice class.
If you will save and
open this file, you will find that there will be necessary client proxy entry
for each of the webmethods present in webservice.
The following prompt ensures that
the webservice is correct and ready to use.
Figure 1
Get the result by running the application
After this, create a button and run the following
javascript function on the button click.
Listing 3
// JScript File
function GetTime()
{
MyService.GetServerTime(onSuccess,onFailed);
return false;
}
Here onSuccess and onFailed are the name of the
functions (similar to delegates) that will be executed eventually at the
success and failure of the AJAX Call. The definitions of them are given below.
Listing 4
function onSuccess(result)
{
alert("Current time is: " + result);
}
Listing 5
function onFailed(result)
{
alert("Error [" + result._statusCode + "] : " + result._message);
}
Finally it will look like this: