DEMO 1: "Hello World!"

The simplest example you can imagine (but maybe not the most fanciful...):

 » Show / hide sample source code

Client (javascript) function HelloWorld()
{
    var pl = new SOAPClientParameters();
    SOAPClient.invoke(url, "HelloWorld", pl, true, HelloWorld_callBack);
}
function HelloWorld_callBack(r)
{
    alert(r);
}
Server (WebMethod - C#) public string HelloWorld()
{
    return "Hello World!";
}

DEMO 2: using parameters

Passing parameters to the Web Service:

 » Show / hide sample source code

Client (javascript) function HelloTo()
{
    var pl = new SOAPClientParameters();
    pl.add("name", document.frmDemo.txtName.value);
    SOAPClient.invoke(url, "HelloTo", pl, true, HelloTo_callBack);
}
function HelloTo_callBack(r)
{
    alert(r);
}
Server (WebMethod - C#) public string HelloTo(string name)
{
    return "Hello " + name + "!";
}

DEMO 3: using .NET framework core classes

Using a date as return type (.NET "DateTime" automatically converted to JavaScript "Date")

 » Show / hide sample source code

Client (javascript) function ServerTime()
{
    var pl = new SOAPClientParameters();
    SOAPClient.invoke(url, "ServerTime", pl, true, ServerTime_callBack);
}
function ServerTime_callBack(st)
{
    var ct = new Date();
    alert("Server: " + st.toLocaleString() + "\r\n[Client: " + ct.toLocaleString() + "]");
}
Server (WebMethod - C#) public DateTime ServerTime()
{
    return DateTime.Now;
}

DEMO 4: void methods

Calling a void method with a long response-time (while waiting for the response an orange box is displayed):

 » Show / hide sample source code

Client (javascript) function Wait()
{
    var duration = parseInt(document.frmDemo.ddSleepDuration[document.frmDemo.ddSleepDuration.selectedIndex].value, 10);
    var pl = new SOAPClientParameters();
    pl.add("seconds", duration);
    var ph = document.getElementById("phWait");
    ph.style.display = "block";
    SOAPClient.invoke(url, "Wait", pl, true, Wait_callBack);
}
function Wait_callBack(r)
{
    var img = document.getElementById("phWait");
    img.style.display = "none";
    alert("Call to \"Wait\" method completed");
}
Server (WebMethod - C#) public void Wait(int seconds)
{
    System.Threading.Thread.Sleep(seconds * 1000);
    return;
}

DEMO 5: Exceptions

Handling exceptions:

 » Show / hide sample source code

Client (javascript) function ThrowException()
{
    try
    {
        var pl = new SOAPClientParameters();
        SOAPClient.invoke(url, "ThrowException", pl, false);
    }
    catch(e)
    {
        alert("An error has occured!");
    }
}
Server (WebMethod - C#) public void ThrowException(int seconds)
{
    throw new Exception();
}

DEMO 6: sync calls

Syncronous call example: server response is delayed 5 seconds using "Wait" method (see demo No. 4). Please note that browser is stuck until response is received:

 » Show / hide sample source code

Client (javascript) function SyncSample()
{
    var pl = new SOAPClientParameters();
    pl.add("seconds", 5);
    var starttime = (new Date).toLocaleTimeString();
    var r = SOAPClient.invoke(url, "Wait", pl, false);
    alert("Operation start time: " + starttime + "\r\nOperation end time: " + (new Date).toLocaleTimeString());
}
Server (WebMethod - C#) public void Wait(int seconds)
{
    System.Threading.Thread.Sleep(seconds * 1000);
    return;
}

DEMO 7: using custom entities (classes)

Leaving the textbox empty, the web method will return a null; entering any value a User object with random property values will be returned:

 » Show / hide sample source code

Client (javascript) function GetUser()
{
    var username = document.frmDemo.txtUsername.value;
    var pl = new SOAPClientParameters();
    pl.add("username", username);
    SOAPClient.invoke(url, "GetUser", pl, true, GetUser_callBack);
}
function GetUser_callBack(u)
{
    if(u == null)
        alert("No user found.\r\n\r\nEnter a username and repeat search.");
    else
        alert(
            "ID: " + u.Id + "\r\n" +
            "USERNAME: " + u.Username + "\r\n" +
            "PASSWORD: " + u.Password + "\r\n" +
            "EXPIRATION: " + u.ExpirationDate.toLocaleString());
}
Server (WebMethod - C#) public User GetUser(string username)
{
    if (username.Trim().Length == 0)
        return null;
    int id = DateTime.Now.Millisecond;
    string password = "PWD_" + DateTime.Now.Ticks.ToString();
    DateTime expirationdate = DateTime.Now.Add(new TimeSpan(1, 0, 0, 0));
    return new User(id, username, password, expirationdate);
}

User class:

[Serializable]
public class User
{
    private int _id = -1;
    private string _username = "";
    private string _password = "";
    private DateTime _expirationdate = DateTime.MinValue;
    public User() { }
    public User(int id, string username, string password, DateTime expirationdate)
    {
        this.Id = id;
        this.Username = username;
        this.Password = password;
        this.ExpirationDate = expirationdate;
    }
    public int Id
    {
        get { return _id; }
        set { _id = value; }
    }
    public string Username
    {
        get { return _username; }
        set { _username = value; }
    }
    public string Password
    {
        get { return _password; }
        set { _password = value; }
    }
    public DateTime ExpirationDate
    {
        get { return _expirationdate; }
        set { _expirationdate = value; }
    }
}

DEMO 8: arrays

Using custom entity arrays. The web method returns an array with 4 User objects (see demo No. 7)

 » Show / hide sample source code

Client (javascript) function GetUsers()
{
    var pl = new SOAPClientParameters();
    SOAPClient.invoke(url, "GetUsers", pl, true, GetUsers_callBack);
}
function GetUsers_callBack(ul)
{
    alert(ul.length + " user(s) found:");
    for(var i = 0; i < ul.length; i++)        
        alert(
            "User No. " + (i + 1) + "\r\n\r\n" +
            "ID: " + ul[i].Id + "\r\n" +
            "USERNAME: " + ul[i].Username + "\r\n" +
            "PASSWORD: " + ul[i].Password + "\r\n" +
            "EXPIRATION: " + ul[i].ExpirationDate.toLocaleString());
}
Server (WebMethod - C#) public User[] GetUsers()
{
    User[] ul = new User[4];
    Random r = new Random();
    for (int i = 0; i < ul.Length; i++)
    {
        int id = r.Next(100);
        string username = "USR_" + id.ToString();
        string password = "PWD_" + id.ToString();
        DateTime expirationdate = DateTime.Now.Add(new TimeSpan((i + 1), 0, 0, 0));
        ul[i] = new User(id, username, password, expirationdate);
    }
    return ul;
}

DEMO 9: ICollection

Custom entity collection (System.Collections.ICollection). The web method returns a UserList object, typed collection of User (see demo No. 7) with 3 elements.

 » Show / hide sample source code

Client (javascript) function GetUserList()
{
    var pl = new SOAPClientParameters();
    SOAPClient.invoke(url, "GetUserList", pl, true, GetUserList_callBack);
}
function GetUserList_callBack(ul)
{
    alert(ul.length + " user(s) found:");
    for(var i = 0; i < ul.length; i++)        
        alert(
            "User No. " + (i + 1) + "\r\n\r\n" +
            "ID: " + ul[i].Id + "\r\n" +
            "USERNAME: " + ul[i].Username + "\r\n" +
            "PASSWORD: " + ul[i].Password + "\r\n" +
            "EXPIRATION: " + ul[i].ExpirationDate.toLocaleString());
}
Server (WebMethod - C#) public UserList GetUserList()
{
    UserList ul = new UserList();
    Random r = new Random();
    for (int i = 0; i < 3; i++)
    {
        int id = r.Next(100);
        string username = "USR_" + id.ToString();
        string password = "PWD_" + id.ToString();
        DateTime expirationdate = DateTime.Now.Add(new TimeSpan((i + 1), 0, 0, 0));
        ul.Add(new User(id, username, password, expirationdate));
    }
    return ul;
}

UserList class:

[Serializable]
public class UserList : System.Collections.CollectionBase
{
    public UserList() { }
    public int Add(User value)
    {
        return base.List.Add(value as object);
    }
    public User this[int index]
    {
        get { return (base.List[index] as User); }
    }
    public void Remove(User value)
    {
        base.List.Remove(value as object);
    }
}

DEMO 10: practical usage

Fill options with AJAX:

 » Show / hide sample source code

Client (javascript) function GetCars()
{
    var cid = document.frmDemo.ddCompany[document.frmDemo.ddCompany.selectedIndex].value;
    if(cid != "")
    {
        // clear car list
        while(document.frmDemo.ddCar.options.length > 0)
            document.frmDemo.ddCar.remove(0);
        // add waiting element
        var o = document.createElement("OPTION");
        document.frmDemo.ddCar.options.add(o);
        o.value = "";
        o.innerHTML = "Loading...";
        // disable dropdown
        document.frmDemo.ddCar.disabled = true;
        // invoke
        var pl = new SOAPClientParameters();
        pl.add("companyid", cid);
        SOAPClient.invoke(url, "GetCars", pl, true, GetCars_callBack);
    }
}
function GetCars_callBack(cl)
{
    // clear car list
    var c = document.frmDemo.ddCar.options.length;
    while(document.frmDemo.ddCar.options.length > 0)
        document.frmDemo.ddCar.remove(0);
    // add first (empty) element
    var o = document.createElement("OPTION");
    document.frmDemo.ddCar.options.add(o);
    o.value = "";
    o.innerHTML = "Please, select a model...";                    
    // fill car list
    for(var i = 0; i < cl.length; i++)
    {
        var o = document.createElement("OPTION");
        document.frmDemo.ddCar.options.add(o);
        o.value = cl[i].Id.toString();
        o.innerHTML = cl[i].Label;
    }
    // enable dropdown
    document.frmDemo.ddCar.disabled = false;
}
Server (WebMethod - C#) public Car[] GetCars(string companyid)
{
    Car[] cl;
    switch (companyid.Trim().ToLower())
    {
        case "vw":
            cl = new Car[]
            {
                new Car(1, "Passat"),
                new Car(2, "Golf"),
                new Car(3, "Polo"),
                new Car(4, "Lupo")
            };
            break;
        case "f":
            cl = new Car[]
            {
                new Car(1, "Stilo"),
                new Car(2, "Punto"),
                new Car(3, "500")
            };
            break;
        case "bmw":
            cl = new Car[]
            {
                new Car(1, "X5"),
                new Car(2, "520")
            };
            break;
        default:
            cl = new Car[0];
            break;
    }
    return cl;
}

Car class:

[Serializable]
public class Car
{
    private int _id = -1;
    private string _label = "";
    public Car() { }
    public Car(int id, string label)
    {
        this.Id = id;
        this.Label = label;
    }
    public int Id
    {
        get { return _id; }
        set { _id = value; }
    }
    public string Label
    {
        get { return _label; }
        set { _label = value; }
    }
}

DEMO 11: Using the SOAP response (xml)

How to use the SOAP response (XmlDocument) in callback method. In this example we show only the Xml in an alertbox, but you can - for example - transform the SOAP response using a stylesheet (XSL).

 » Show / hide sample source code

Client (javascript) function GetSoapResponse()
{
    var pl = new SOAPClientParameters();
    SOAPClient.invoke(url, "HelloWorld", pl, true, GetSoapResponse_callBack);
}
function GetSoapResponse_callBack(r, soapResponse)
{
    alert(soapResponse.xml);
}
Server (WebMethod - C#) public string HelloWorld()
{
    return "Hello World!";
}