Reputation: 379
I am building a WCF service in C# in which I would like to be able to return multiple values from some of my functions. The code below appears to do this:
[WebMethod]
public void ReturnMultipleValues(int startingValue)
{
JavaScriptSerializer ser = new JavaScriptSerializer();
var jsonData = new { FirstValue = startingValue, SecondValue = startingValue * 2 };
Context.Response.Write(ser.Serialize(jsonData));
}
I am trying to access this function through an ajax call in JavaScript code:
function runTestService() {
$.ajax({
type: "POST",
url: "http://localhost:12345/WebServices/MyService.asmx/ReturnMultipleValues",
contentType: "application/json;charset=utf-8",
data: "{ 'startingValue' : 6 }",
dataType: "json",
done: function(data) {
var firstValue = data.FirstValue;
var secondValue = data.SecondValue;
alert("First: " + firstValue + ", Second: " + secondValue);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error: " + errorThrown);
}
});
}
When I execute the above JavaScript code, the function in the .done
portion never executes. When I check Fiddler, however, I see that the function in my service did execute properly and returned the correct values in the JSON.
Is there another way I should code either the service or the ajax call to it?
Upvotes: 0
Views: 892
Reputation: 9632
You are not supposed to write to Context.Response
by yourself. Just return an object from method and let the framework do it for you
[WebMethod]
public object ReturnMultipleValues(int startingValue)
{
var jsonData = new { FirstValue = startingValue, SecondValue = startingValue * 2 };
return jsonData;
}
And you have to consider the fact web service wraps json repsonse in object with d
property
{
"d": {
"FirstValue": 6,
"SecondValue": 12
}
}
So update js as well
done(function (data) {
data = data.d;
var firstValue = data.FirstValue;
var secondValue = data.SecondValue;
alert("First: " + firstValue + ", Second: " + secondValue);
});
Upvotes: 2