jQuery with ASP.NET Json Web Services

June 19th, 2008 by Steve Gentile Leave a reply »

I’m on a ‘pro-jQuery’ kick, as I’m using it on my project and it’s fantastic. 

There is a good article on comsuming ASP.NET Json Web Services with jQuery:

Using jQuery to Consume ASP.NET JSON Web Services

I actually ran into one of the problems discussed with jQuery and sending empty data to a service

ie.

$.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "WebService.asmx/WebMethodName", data: "{}", dataType: "json" });

Above you can see the ‘data: “{}” – with the following explanation:

“The “{}” data parameter represents an empty JSON object, which you can think of as the JSON equivalent of null.

Supplying this parameter will convince jQuery to correctly send the content-type that we’ve supplied,

while it will be safely ignored by the web service.”

As a side note, there are times I want to send json data to a MVC action.

Here is an example of this (using Prototype – but same applies to jQuery).  What is critical here is understanding how to read the JSON data being sent to the action – as described below you can retrieve this within the requests ‘InputStream’ property:

“Within this method the code takes a peek at the current Request, specifically the incoming JSON string contained within the request’s InputStream property. This is where I’ll use my JsonHelper class, which makes it a snap to parse an HTTP Request into a JSON object”

Advertisement

1 comment

  1. Brady Gaster says:

    Thanks for the link to my post. If you or anyone else knows of a “better” way to read JSON data coming in to the server I’d be all ears. This seemed the best, no-bones-about-it methodology and so far I’m really happy with it in a few areas.

    Thanks again. Looking forward to a better way if one’s been discovered.

Leave a Reply