views:

2957

answers:

3

The following code executes properly when the data key has no data to send, i.e. data: "{}" an empty JSON object and the webservice takes no parameters. I would like to post some data to the webservice but I am running into trouble.

When I try to set this to data:"{'name':'Niall','surname':'Smith'}", I get an error

{"Message":"Invalid web service call, missing value for parameter: \u0027json\u0027.","StackTrace":"   at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters)\r\n   at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)\r\n   at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}

The webservice is not executed.

This is my Jquery call to post my data back to the server.

    $.ajax({
        type: "POST",
        url: "/WebServices/BasketServices.asmx/AddItemToBasket",
        data: "{'name':'niall'}", // Is this Correct??
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnItemAddedSuccess
    });
function OnItemAddedSuccess(result,eventArgs) {
    //deserialize the JSON and use it to update the Mini Basket
    var response = JSON.parse(result.d);
}

here is my WebService

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class BasketServices : System.Web.Services.WebService
{
    [WebMethod(true)]
    public string AddItemToBasket(string json)
    {
       //do stuff
       return myString.toJSON();
    }
}

What could the problem be? Is it the format of the JSON data to be posted? Could it be that I haven't set the correct Attributes on my WebService. What about the problems alluded to in Dave Ward's post

I have tried everything I can think of. Does anyone have any ideas?

+1  A: 

This should work. You should pass json as a string, with a parameter name 'json' (which is the same as parameter name in your web method.

data: "{json: '{\'name\':\'niall\'}'}",

Chetan Sastry
+2  A: 

I think the webservice expects the parameter json to be set. Try this AJAX call :

var data = {'name':'niall'};

$.ajax({
    type: "POST",
    url: "/WebServices/BasketServices.asmx/AddItemToBasket",
    data: "json=" + JSON.stringify(data),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: OnItemAddedSuccess
});

where JSON.stringify() is a method like the one found in the "official" implementation : http://json.org/js.html

Wookai
A: 

This always happens to me when I don't wrap the string data with double quotes

slf