Friday, May 1, 2009

Call asp.net Webservice from javascript.

How to call asp.net webservice from javascript.

In asp.net we can develope webservices.we can call webservice in our application by adding webreferance to that webservice.In asp.net 3.5 We can also call webservice using javascript. asp.net 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 asp.net 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 = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class WebService : System.Web.Services.WebService
{
public WebService()
{
}
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
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">
<Services>
<asp:ServiceReference Path="~/WebService.asmx" />
</Services>
<Scripts>
<asp:ScriptReference Path="~/WebService.asmx.js" />
</Scripts>
</asp:ScriptManager&



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


var HelloWorldResult="";
function HelloWorld(name)
{
MyService.WebService.HelloWorld(name,HelloWorldSuccess,HelloWorldFailure,null);
}
function HelloWorldSuccess(response)
{
alert(response.Name);
}
function HelloWorldFailure(error)
{
alert(error);
}



(6)Call Helloworld Function in Your aspx Page.

<script>
HelloWorld("Haresh!!!Thi is Call From javascript");
</script>


Hope this will help you.

Thanks.

1 comment:

  1. can you give the example of match the value from database in asp.net

    ReplyDelete

Comments posted on ASP.Net Ajax Tutorials Blog are moderated and will be approved only if they are on-topic and not abusive. Please email me or my team for tech-support or blogging related questions. Avoid including website URLs in your comments - Thanks Author