Partager via


Sys.Net.WebServiceProxy invoke Method

Invokes the specified Web service method.

var webRequest = Sys.Net.WebServiceProxy.invoke(ServicePath, methodName, useGet, params, onSuccess, onFailure, userContext, timeout, enableJsonp, jsonpCallbackParameter);

Parameters

Parameter

Description

ServicePath

A string that contains the Web service URL. ServicePath can be set to a fully qualified URL (https://www.mySite.com/myService.asmx), to an absolute URL without the host name or the fully qualified domain name (FQDN) (/myService.asmx), or to a relative URL (../myService.asmx).

The WebRequest class makes sure that the URL is converted into a form that is usable by network executors.

methodName

A string that contains the name of the Web service method to invoke.

useGet

(Optional) false to set the Web request HTTP verb to POST; otherwise, true. The default is false.

Note

The call to the Web service will fail if the verb defined by useGet does not match the ScriptMethodAttribute setting of the corresponding Web server method. For example, the following attribute code (in C#) requires that the call be made with a GET verb:

[ScriptMethod(UseHttpGet=true)]

params

(Optional) A JavaScript dictionary that contains named properties (fields) that correspond to the parameters of the method to call, as in the following example:

{"param1":196610,"param2":"Hello"}

Note

The field names in the dictionary must match the names of Web service methods.

If the Web server method does not take any parameters, params can be left out or can be null or an empty dictionary ({}). Any values that you pass are then ignored.

If the dictionary contains key/value pairs that do not correspond to a parameter of the Web server method, they are ignored.

onSuccess

(Optional) The function that is invoked as a callback if the Web service method call returns successfully.

onSuccess can be set to null if you do not need it and if you must specify a value for the remaining parameters.

If no callback function is provided, no action is taken when the Web service method finishes successfully.

onFailure

(Optional) The function that is invoked as a callback if the Web service method call fails.

onFailure can be set to null if you do not need it and if you must specify a value for the remaining parameters.

If no callback function is provided, no action is taken if an error occurs during the Web service method call.

userContext

(Optional) Any user-specific information. userContext can be any JavaScript primitive type, array, or object.

The contents of userContext are passed to the callback functions (if any). If userContext is not provided, null is passed to the callback function.

timeout

(Optional) The time in milliseconds that the network executor must wait before timing out the Web request. timeout can be an integer or null. By defining a time-out interval, you can control the time that the application must wait for the callback to finish.

enableJsonp

(Optional) true to indicate that the service supports JSONP for cross-domain calls; otherwise, false.

jsonpCallbackParameter

(Optional) The name of the callback parameter for the JSONP request. The default is "callback".

Return Value

The WebRequest instance that is used to call the method. This instance can be used to stop the call.

Remarks

The Web service path is assigned at run time, not through the path attribute of the ServiceReference element of the ScriptManager control in the page.

When you call the invoke method from JavaScript code, an asynchronous Web request is issued for the Web service method specified in methodName. When the request returns, the appropriate JavaScript callback function (succeeded or failed) is called.

You do not have to pass callback functions or user context as parameters in the method call. Instead, you can specify default callback or user context settings as properties of the generated proxy object. For more information, see Generated Proxy Classes.

Example

The following example shows how to use invoke to call a Web service method. The example shows a Web page, a client script, and a Web service called by the page through the client script.

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

</script>

<html xmlns="https://www.w3.org/1999/xhtml" >
 <head id="Head1" runat="server">

        <style type="text/css">
            body {  font: 11pt Trebuchet MS;
                    font-color: #000000;
                    padding-top: 72px;
                    text-align: center }

            .text { font: 8pt Trebuchet MS }
        </style>

        <title>Web Service Proxy</title>


</head>
<body>
    <h2>WebServiceProxy Example</h2>

        <form id="form1" runat="server">
            <asp:ScriptManager runat="server" ID="scriptManager">
                <Scripts>
                    <asp:ScriptReference Path="WebServiceProxy.js" />
                </Scripts>
            </asp:ScriptManager>  

            <table style="font-size:12px">
                <tr>
                    <td>Select Web Service and Method:</td>
                    <td>
                        <select id="SelectionId"    
                            onchange="OnSelectMethod(); return false;">
                            <option value="WebService.asmx" selected>GetServerTime</option>
                            <option value="WebService.asmx">GetGreetings</option>
                            <option value="WebService.asmx">PostGreetings</option>
                        </select>
                    </td>
                </tr>
            </table> 


           <hr />

            <!-- Display results. -->
            <p>
                <span  style="background-color:Aqua" id="ResultId"></span>
            </p>


        </form>
</body>
</html>
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

</script>

<html xmlns="https://www.w3.org/1999/xhtml" >
 <head id="Head1" runat="server">

        <style type="text/css">
            body {  font: 11pt Trebuchet MS;
                    font-color: #000000;
                    padding-top: 72px;
                    text-align: center }

            .text { font: 8pt Trebuchet MS }
        </style>

        <title>Web Service Proxy</title>


</head>
<body>
    <h2>WebServiceProxy Example</h2>

        <form id="form1" runat="server">
            <asp:ScriptManager runat="server" ID="scriptManager">
                <Scripts>
                    <asp:ScriptReference Path="WebServiceProxy.js" />
                </Scripts>
            </asp:ScriptManager>  

            <table style="font-size:12px">
                <tr>
                    <td>Select Web Service and Method:</td>
                    <td>
                        <select id="SelectionId"     
                            onchange="OnSelectMethod(); return false;">
                            <option value="WebService.asmx" selected>GetServerTime</option>
                            <option value="WebService.asmx">GetGreetings</option>
                            <option value="WebService.asmx">PostGreetings</option>
                        </select>
                    </td>
                </tr>
            </table> 


           <hr />

            <!-- Display results. -->
            <p>
                <span  style="background-color:Aqua" id="ResultId"></span>
            </p>


        </form>
</body>
</html>
var webMethod;
var webServicePath;

// This function shows how to use the 
// WebServiceProxy.invoke method without passing
// parameters.
function GetTime()
{
    Sys.Net.WebServiceProxy.invoke(webServicePath, 
        webMethod, false,{}, OnSucceeded, 
        OnFailed,"User Context",1000000);

}

// This function shows how to use the 
// invoke method passing
// parameters and using the GET verb.
// The dictionary field names must match the 
// related Web service method parameter names.
function GetGreetings() 
{
    Sys.Net.WebServiceProxy.invoke(webServicePath, 
        webMethod, true,
        {"greeting":"Have a nice day", "name":" to You (via GET)!"},
        OnSucceeded,OnFailed, "User Context",100);

}

// This function shows how to use the 
// invoke method passing parameters and using the POST verb.
// The dictionary field names must match the 
// related Web service method parameter names.
function PostGreetings() 
{
    Sys.Net.WebServiceProxy.invoke(webServicePath, 
        webMethod, false,
        {"greeting":"Have a nice day", "name":" to You (via POST)!"},
        OnSucceeded,OnFailed, "User Context",100);

}

// This is the callback function invoked 
// if the Web service succeeded.
function OnSucceeded(result, eventArgs)
{

    // Display the result.
    var RsltElem = 
        document.getElementById("ResultId");
    RsltElem.innerHTML = result;

}


// This is the callback function invoked 
// if the Web service failed.
function OnFailed(error)
{
    // Display the error.    
    var RsltElem = 
        document.getElementById("ResultId");
    RsltElem.innerHTML = 
    "Service Error: " + error.get_message();
}



// This function process the user's selection.
function OnSelectMethod()  
{
    // Get the user's selected method.
    var selectionIndex = 
        document.getElementById("SelectionId").selectedIndex;
    webMethod = 
        document.getElementById("SelectionId").options[selectionIndex].text;

    // Get the related Web service path.
    webServicePath = 
        document.getElementById("SelectionId").value;


   // Call selected Web service method.
   switch (webMethod)
   {
    case "GetServerTime":
        GetTime();

        break;

    case "GetGreetings":
        GetGreetings();
        break;

    case "PostGreetings":
        PostGreetings();
        break;

    default:
        alert("default");
   }
}

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
<%@ WebService Language="C#" Class="Samples.AspNet.WebService" %>

using System;
using System.Web;
using System.Web.Services;
using System.Xml;
using System.Web.Services.Protocols;
using System.Web.Script.Services;

namespace Samples.AspNet
{
    [WebService(Namespace = "https://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ScriptService]
    public class WebService : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(UseHttpGet = true)]
        public string GetGreetings(string greeting, 
               string name)
        {
            return greeting + " " + name;
        }


        [WebMethod]
        [ScriptMethod(UseHttpGet = false)]
        public string PostGreetings(string greeting,
               string name)
        {
            return greeting + " " + name;
        }

        [WebMethod]
        public string GetServerTime()
        {

            string serverTime =
                String.Format("The current time is {0}.", DateTime.Now);

            return serverTime;

        }


    }


}

See Also

Reference

Sys.Net.XMLHttpExecutor Class

Sys.Net.WebRequestManager Class

Other Resources

Calling Web Services from Client Script in ASP.NET AJAX