Friday, May 1, 2009

Call Webservice from javascript.

How to call webservice from javascript.

In we can develope webservices.we can call webservice in our application by adding webreferance to that webservice.In 3.5 We can also call webservice using javascript. 3.5 also resurns JSON in response to call of webservice.this is possible using namespance System.Web.Script.Services. this namespace has a class called ScriptService.using this class we can call webservice using javascript.

(1)this is WebService.Cs of My webservice.

using System.Web.Services;
using System.Web.Script.Services;
namespace MyService
public class User
public int ID;
public string Name;
[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService
public WebService()
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public User HelloWorld(string Name)
User u = new User();
u.ID = 1;
u.Name = Name;
return u;

(2)Add ScriptManager to your aspx page.
(3)Give referance to webservice in ScriptManager
(4)Give referance to script which will handle response of webservice in ScriptManager

<asp:ScriptManager ID="ScriptManager2" runat="server">
<asp:ServiceReference Path="~/WebService.asmx" />
<asp:ScriptReference Path="~/WebService.asmx.js" />

(5)add this javascript in WebService.asmx.js

var HelloWorldResult="";
function HelloWorld(name)
function HelloWorldSuccess(response)
function HelloWorldFailure(error)

(6)Call Helloworld Function in Your aspx Page.

HelloWorld("Haresh!!!Thi is Call From javascript");

Hope this will help you.