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 JavaScript 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.tempuri.org/")]
[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.
	}
});

Comments

#1
Sanno Says:
On March 25th, 2012 at 8:20 PM

I have json object as below

var model = {“d”:[
{"AttachmentId":263,"FileName":"dummy document 1.docx","DateAdded":"2009-10-06 11:46:12","FileSize":"9,7 KB"},
{"AttachmentId":264,"FileName":"dummy document 2.docx","DateAdded":"2009-10-07 11:46:12","FileSize":"9,7 KB"},
{"AttachmentId":265,"FileName":"dummy document 11.docx","DateAdded":"2009-10-08 11:46:12","FileSize":"9,7 KB"},
{"AttachmentId":266,"FileName":"dummy document 53.docx","DateAdded":"2009-10-09 11:46:12","FileSize":"9,7 KB"},
{"AttachmentId":271,"FileName":"another dummy document.docx","DateAdded":"2009-10-14 17:14:29","FileSize":"9,7 KB"},
{"AttachmentId":272,"FileName":"error.png","DateAdded":"2009-10-16 18:58:28","FileSize":"20,9 KB"},
{"AttachmentId":273,"FileName":"GUI - ugly error message.png","DateAdded":"2009-10-16 19:02:32","FileSize":"13,8 KB"},
{"AttachmentId":274,"FileName":"message.txt","DateAdded":"2009-10-16 19:09:34","FileSize":"1,5 KB"}
]};

i want to send this json string into asp.net web service and web service should process the string in send back to the client code .
I have sent the string in to web service but i don’t know how to convert it in web service??

#2
Ramesh Gurunathan Says:
On November 6th, 2012 at 8:47 AM

Thanks very much. Your tips really helped me. Keep post new tips.

Leave a Comment