Saturday 4 July 2009

Sending Complex JavaScript Objects to WCF and Web Services

Example 1 - Sending dictionary to a WebMethod or PageMethod:

[WebMethod]
public static string SendDictionary(Dictionary<string,string> dictionary)
{
return "Success";
}

Sending objects using AJAX:

function SendDictionary() {
var dictionary = CreateDictionary();
PageMethods.SendDictionary(dictionary, sendDictionarySucceededHandler, sendDictionaryFailedHandler);
}

function CreateDictionary() {
var dictionary = new Object();
dictionary["Filter1"]= "SelectedValue1";
dictionary["Filter2"]= "SelectedValue2";
return dictionary;
}

Example2-Sending list of objects to a WebMethod or PageMethod:

[WebMethod]
public static string SendPeople(List<string> people)
{
return "Success";
}

Sending objects using AJAX:

function SendPeople() {
var people = CreatePeople();
PageMethods.SendPeople(people, sendPeopleSucceededHandler, sendPeopleFailedHandler);
}

function CreatePeople() {
var result = new Array();
var object1 = new Object();
object1.FirstName = "FirstName1";
object1.LastName = "LastName1";
result[0] = object1;

var object2 = new Object();
object2.FirstName = "FirstName2";
object2.LastName = "LastName2";
result[1] = object2;

return result;
}
Example3 - Sending Dictionary to a WCF service
You must use JSON to do so.
function SendDictionary()
{var dictionary = CreateDictionaryForWCF();
PageMethods.SendDictionary(dictionary, sendDictionarySucceededHandler, sendDictionaryFailedHandler);}
function CreateDictionaryForWCF()
{
var dictionary = new Array();
dictionary[0]= AddJSONItem("Filter1", "SelectedValue1");
dictionary[1]= AddJSONItem("Filter2", "SelectedValue2");
return dictionary;}
function AddJSONItem(key, value){ return {"Key": key, "Value": value};}

More details:

No comments: