Pages

Monday, December 26, 2011

Invoking webservice from Javascript

Microsoft Ajax.net introduced a brand new concept of Page Methods, the problem with Page methods are we can’t use page methods in Master Pages or in Usercontrols. From an OOP presepective, it is not good to write the code every page, so the work around is using the Ajax enabled webservices. There is not big difference between common webservices and Ajax enabled webservice, which allows javascript to access web methods. To make a web service as Ajax enabled, you need to give some [System.Web.Script.Services.ScriptService] attribute to the class name, and the Master Page you need to refer this service using the ASP.Net script manager
1
2
3
4
5
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" EnablePartialRendering="true">
<services>
<asp:ServiceReference Path="~/MyService.asmx" />
services>
asp:ScriptManager>
Then you can call the web method in the webservice using MyService.MethodName() syntax.
Webservice code.
1
2
3
4
5
6
7
8
9
[System.Web.Script.Services.ScriptService]
public class MyService: System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return ("Hello World, this is from a webservice method");
}
}
And refer the service in the Page using script manager.
1
2
3
4
5
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" EnablePartialRendering="true">
<services>
<asp:ServiceReference Path="~/MyService.asmx" />
services>
asp:ScriptManager>
And in the javascript
1
2
3
4
5
6
7
8
function InvokeWebMethod()
{
MyService.HelloWorld(Callback);
}
function Callback(result)
{
alert(result);
}
The InvokeWebMethod function will call the webservice webmethod, and after executing the call, it returns the result to the function “Callback”. In this function, it alerts the results, which gets as the input parameter. You can get custom collections and objects on the client side using this method. You also need some modifications in the web.config file, but by default VS 2008, does this configuration for you.

No comments: