Pages

Monday, November 29, 2010

Calling Web service using javascript overloaded web method

Here is the code for calling the webservice using javascript with overloaded web methods
Default.aspx
<script type="text/javascript">
       function CallWebService() {
           WS.a(ReuqestCompleteCallback, RequestFailedCallback);
           WS.b('Amit',ReuqestCompleteCallback, RequestFailedCallback);
       }
       function ReuqestCompleteCallback(result)
       {
           // Display the result.
           var divResult = document.getElementById("divMessage");
           divResult.innerHTML = result;
       }
       function RequestFailedCallback(error) {
           var stackTrace = error.get_stackTrace();
           var message = error.get_message();
           var statusCode = error.get_statusCode();
           var exceptionType = error.get_exceptionType();
           var timedout = error.get_timedOut();
 
           // Display the error.  
           var divResult = document.getElementById("Results");
           divResult.innerHTML = "Stack Trace: " + stackTrace + "  " +  "Service Error: " + message + "  " +  "Status Code: " + statusCode + "  " +  "Exception Type: " + exceptionType + "  " +  "Timedout: " + timedout;
          }
    </script>
<form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Services>
            <asp:ServiceReference Path="~/WS.asmx" />
        </Services>
        </asp:ScriptManager>
    </div>
    <div>
            <input type="button" value="Call Web Service" onclick="CallWebService();" />
        </div>
        <div id="divMessage">
        </div>
    </form>
WebService == WS.asmx
1. You can't use method overloading in web service since wsdl 1.1 does not supports it. That is the reason why you  are using alias name for the overloaded methods
2. When you use alias name then the webmethod is exposed as alias name instead of original name in the wsdl. So you need call your webmethod using alias name from your client. Your client have no idea about the original method name when alias is used. 
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WS : System.Web.Services.WebService
{
    public WS()
    {
  }
  [WebMethod(Description = "HelloWorld Returns 'Hello World'", MessageName = "a")]
    public string HelloWorld()
    {
        return "Hello World";
    }
    [WebMethod(Description = "HelloWorld Returns Given Name", MessageName = "b")]
    public string HelloWorld(string Name)
    {
        return Name;
    }
}

1 comment: