Returning JSON from an ASP.NET Web Service
If you’re having trouble with getting jQuery to talk to your ASP.NET web service, I may have some tips to ease your pain.
#1: It’s not JSON!
That’s right, even though your WebMethod consumes and returns JSON, you actually have to send a formatted string instead of a pure JSON object:
JavaScript:
var BadArguments = { FirstName: "John", LastName: "Doe" }; // BAD
var GoodArguments = '{ "FirstName": "John", "LastName": "Doe" }'; // GOOD
This means that the JSON used by ASP.NET web services is not portable. To get around this, I created a little JavaScript function that handles one-dimensional associative arrays and converts them to “MS-JSON.” You may want to adapt this function to your needs since it explicitly doesn’t handle “objects” such as arrays or dates:
JavaScript:
function GenerateAspNetJsonString(MyArray) {
var StrOut = '{';
for (var key in MyArray) {
if ('object' != typeof MyArray[key]) {
// The type is not an object, so we can write it down as a string:
StrOut += '"' + key + '":"' + escape(MyArray[key]) + '",'
}
}
// Strip the trailing comma and return:
return StrOut.substr(0, StrOut.length - 1) + '}';
}
#2: Check your Attributes
Chances have that you already marked your web method with the following code:
VB.NET:
<WebMethod(Description:="Does something.")> _ <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _ Public Function MyMethod(ByVal Something as String) As String ...
C#:
[WebMethod(Description = "Does something.")] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public string MyMethod(string Something) ...
But make sure that you have also marked the Web Service’s class with the ScriptService (short for ScriptServiceAttribute) attribute as well. This is not automatically done by Visual Studio when the code is generated, so you’ll have to do it manually:
VB.NET:
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _ <System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _ <ScriptService()> _ Public Class MyWebService Inherits System.Web.Services.WebService ...
C#:
[WebService(Namespace = "http://www.williamsportwebdeveloper.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class MyWebService : System.Web.Services.WebService { ...
#3: When all else fails
Check your XmlHttpRequest’s errors, since ASP.NET actually returns quite a bit of useful information in debug mode. Using jQuery, you can add an error handler to your $.ajax function call:
JavaScript:
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '/MyWebService.asmx/MyWebMethod',
// notice the usage of the function provided in #1:
data: GenerateAspNetJsonString({
FirstName: 'John',
LastName: 'Doe'
}),
dataType: 'json',
error: function (jqXHR, textStatus, errorThrown) {
// responseText contains all of the interesting
// bits and pieces:
alert(jqXHR.responseText);
},
success: function (msg) {
// do something with msg.d, eval() to
// to retrieve the data.
}
});
Scriptionary 
Leave a Comment