views:

114

answers:

3

I'm trying to post data to a webservice (asp.net 3.5), like below (two variants, one commented):

var array = [3, 2, 5, 1, 7];
var jsonString = JSON.stringify(array);
//var jsonString = '{ "firstName": "John", "lastName": "Smith", "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021" }, "phoneNumber": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ] }'

$.ajax({
    type: "POST",
    url: "WebService2.asmx/AddRoute",
    data: jsonString,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    processData: "false",
    error: function(msg) {
        alert('error' + msg.toString);
    }
});

So I need a matching webmethod to recieve it. Something like this:

[WebMethod]
public string AddRoute(/* xxx */)
{
    //handle data
}

Could someone please elaborate on how I can fetch the data, where I've typed "xxx"? I would have thought "int[] array" would do the trick, but it's not working. Any help would be greatly appreciated :)

A: 

Instead of an .asmx web service, you should just expose an asp.net mvc action method. This post by Phil Haack shows just how easy it is to accept strongly typed json data (including arrays):
http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx

Joel Martinez
R0MANARMY, and Joel, thank you very much for your replies!I got it working the way it is described on 'encosia' with a web service. So I'm sticking to that for now. However I will look into mvc as well later on. Not that I plan to recieve any errors :D but if I did they would obviously be easier to handle with mvc.Again, thank's for taking time. I really appreciate it!
A: 

I'm not familiar with ASP.NET but, there should be some way for you to obtain request parameters that are being passed using jQuery.ajax().

$.ajax({ type: "POST", url: "WebService2.asmx/AddRoute", data: {'some_data': jsonString}, contentType: "application/json; charset=utf-8", dataType: "json", processData: "false", error: function(msg) { alert('error' + msg.toString); } });

The request parameter would be some_data. From your controller, you can retrieve the request parameter without it being passed as an argument to your function.

I apologize for it being vague as I come from a Python/Pylons background.

-Mark Huang

Mark
A: 

Try something like the following code:
You could have int[] instead of string[] as well


[WebInvoke(UriTemplate = "ServiceName", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, Method = "POST")]
public string ServiceName(string[] ids)

Ajaxe