views:

3918

answers:

2

I've been having problems with this code I had spent the last 3 hours digging around and trying to find an answer. As I wasn't successful, I will just post the code and ask which kind of parameters I should have on my web service to handle this request:

var args = [{ key: 'myId', value: 'myValue' }, { key: 'myOtherId', value: 'myOtherValue'}];
var dataToSend = { name: 'fooId', value: 'fooValue', args: args };
$.ajax({
type: 'POST',
url: 'fooURL',
data: dataToSend,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: OnSuccess,
error: OnError
});

Now, which kind of signature I should have to be able to get my "dataToSend"?

I've tried:

[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Foo(string name, object value, List<Args> args)
{
    return "OK";
}

public class Args
{
    public string key { get; set; }
    public object value { get; set; }
}

and

[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Foo(string name, object value, object[] args)
{
    return "OK";
}

and also

[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Foo(dataToSend dataToSend)
{
    return "OK";
}

public class dataToSend
{
    public string name { get; set; }
    public object value { get; set; }
    public List<Args> args = new List<Args>();

}
public class Args
{
    public string key { get; set; }
    public object value { get; set; }
}

EDITED: I still haven't found an answer. Anyone?

A: 

If you're working with JSON-enabled .NET WebServices/WebMethods... my tips are:

  • Be very careful with web.config configuration. Use it to enable big parameters, POST method and JSON.

  • Use a framework to handle Object serialization e deserialization. I would recommend NewtonSoft's Json.NET.

I don't think ASP.NET automagically do it for you, your parameters are always strings. You should take that strings, deserialize it and turn it to an array of objects.

wtaniguchi
I think it does. Check this out (although it's MVC the same concept should be applied for web forms): http://blogger.forgottenskies.com/?p=243
afgallo
+3  A: 

Try passing the data as a string, not an object, ie:

$.ajax( {
    ...
    data : '{ a: 2, b: 3 }',
    ...
} );

The reasoning for this is that if you specify an object as data then jQuery serializes the data using query string format, whereas the server is expecting JSON format directly.

This happens despite telling jQuery to use JSON as the data type - it seems to only relate to the result, not the request payload sent to the server.

Everything else you have there looks correct to me.

Sam
Pretty sure Sam has it here. Check http://elegantcode.com/2009/02/21/javascript-arrays-via-jquery-ajax-to-an-aspnet-webmethod/ for more info. Assuming the string fixes it, I think it'll be the first syntax.
Dan F