tags:

views:

8090

answers:

4

I created an ASMX file with a code behind file. It's working fine, but it is outputting XML.

However, I need it to output JSON. The ResponseFormat configuration doesn't seem to work. My code-behind is:

[System.Web.Script.Services.ScriptService]
public class _default : System.Web.Services.WebService {
    [WebMethod]
    [ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)]
    public string[] UserDetails()
    {
        return new string[] { "abc", "def" };
    }
}
+2  A: 

What I'm using looks like this :

[WebMethod(EnableSession = true)]
public string Method()
{
 //do stuff...
  var ots = new {prop="stringValForExample"}; // create an anonymouse object
  return JavaScriptConvert.SerializeObject<object> ( ots );      
}

and with jquery - on success :

success : function(res){
 var objReturned = eval("("+res.d+")");
 //now in objReturned.prop - you should have your value.

The JavascriptConvert is from Newtonsoft.Json library.

sirrocco
+1 for JavascriptConvert!
BobbyShaftoe
+9  A: 

From WebService returns XML even when ResponseFormat set to JSON:

Make sure that the request is a POST request, not a GET. Scott Guthrie has a post explaining why.

Though it's written specifically for jQuery, this may also be useful to you:
http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/

Pavel Chuchuva
A: 

Hi,

Are you calling the web service from client script or on the server side?

You may find sending a content type header to the server will help, e.g.

'application/json; charset=utf-8'

On the client side, I use prototype client side library and there is a contentType parameter when making an Ajax call where you can specify this. I think jQuery has a getJSON method.

paulie
+2  A: 

A quick gotcha that I learned the hard way (basically spending 4 hours on Google), you can use PageMethods in your ASPX file to return JSON (with the [ScriptMethod()] marker) for a static method, however if you decide to move your static methods to an asmx file, it cannot be a static method.

Also, you need to tell the web service Content-Type: application/json in order to get JSON back from the call (I'm using jQuery and the 3 Mistakes To Avoid When Using jQuery article was very enlightening - its from the same website mentioned in another answer here).

Redbeard 0x0A