Today I will describe how to call a Web Service from JavaScript in ASP.Net.
Steps are as follows…
Step 1: First create a new AJAX enabled Web Application.
Step 2: Add new Web Service to the project. Let’s say WebService.asmx
Step 3: To allow this Web Service to be called from script
add the following attribute to the Web Service declaration part:
[System.Web.Script.Services.ScriptService]
Step 4: Now we need a Web Method that we will call from client-side JavaScript. Let us define it like this:
[WebMethod]
public string GetServerResponse(string text)
{
if (text == string.Empty)
throw new Exception("Web Service Exception: Enter some text");
return string.Format("Web Service Success: {0} " , DateTime.Now.ToString());
}
Step 5: Add ScriptManager in our .aspx page.
<form id="form1" runat="server" >
     <asp:ScriptManager ID="ScriptManager1" runat="server" >
     </asp:ScriptManager >
    </form >
Step 6: Add ServiceReference to the Services collection and specify Path to the desired service.
    <asp:ScriptManager ID="ScriptManager1" runat="server" >
        <Services >
            <asp:ServiceReference Path="~/WebService.asmx" />
        </Services >
    </asp:ScriptManager >
Step 7: Now create the javascript function as follows
<script language="javascript" type="text/javascript">
        function SendRequest() {
            var val = document.getElementById('<%= txtName.ClientID %>').value;
            WebService.GetServerResponse(val, OnComplete, OnError, OnTimeOut);
            return false;
  }
  function OnComplete(arg)
  {
      alert(arg);
  }
  function OnTimeOut(arg)
  {
   alert("timeOut has occured");
  }
  function OnError(arg)
  {
   alert("error has occured: " + arg._message);
  }
    </script >
Step 8: To call this javascript create a textbox and a button in your aspx Page.
<asp:textbox id="txtName" runat="server" >
</asp:textbox >
<asp:button id="btnCallService" runat="server" text="Call Service" onclientclick="javascript:return SendRequest();" ></asp:button >
 
1 comment:
Hey Man, Really it is a very good job...Keep it up...
Post a Comment