Thursday, April 18, 2013

Consuming a web service using ASP .NET AJAX


It is easy to call web services with the native ASP .NET AJAX, which would automatically take care all of the gritty details. It takes two steps:
First, add a ServiceReference to the ScriptManager control in the web form, as such:

<asp:ScriptManager ID="_scriptManager" runat="server">
  <Services>
    <asp:ServiceReference Path="dummywebservice.asmx" />
  </Services>
</asp:ScriptManager>

Second, call any web methods defined in the web service by passing the necessary parameters and a callback function. The callback will be invoked once the data is returned from server. The following is a complete example of how we call a web service using ASP .NET AJAX.


<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Services" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html  >
<head id="Head1" runat="server">
<title>ASP.NET AJAX Web Services: Web Service Sample Page</title>
 <script type="text/javascript"  src="http://ajax.googleapis.com/ajax/libs/jQuery/1.2.6/jQuery.min.js">  
</script> 
  <script type="text/javascript">
      function OnSayHelloClick() {
          var txtName = $get("name");
          dummyWebservice.HelloToYou(txtName.value, SayHello);
      }
      function SayHello(result) {
          alert(result);
      }
  </script> 
</head>
<body>
   <form id="form1" runat="server">
    <asp:ScriptManager ID="_scriptManager" runat="server">
      <Services>
        <asp:ServiceReference Path="dummyWebsevice.asmx" />
      </Services>
    </asp:ScriptManager>
    <h1> ASP.NET AJAX Web Services: Web Service Sample Page </h1>
     Enter your name:
        <input id="name" />
        <br />
        <input id="sayHelloButton" value="Say Hello"
               type="button" onclick="OnSayHelloClick();" />
    </form>
</body>
</html>
However as we have mentioned before, ASP .NET AJAX is rather heavy-handed and carries hefty performance penalties. In comparison, jQuery is superior in its promise of “less code do more”.

No comments:

Post a Comment