9

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?

nialljsmith
  • 474
  • 1
  • 7
  • 18

4 Answers4

12

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
  • 20,883
  • 16
  • 73
  • 86
  • +1, this got me past my problem. Since he's expecting json to be a string and not a complex type in service, it should actually be `var data = {'json':'niall'};` followed by `data: JSON.stringify(data),` later on. – DougJones Dec 14 '11 at 19:02
5

The solution above did not work for me. So instead i did the following. 1.) make sure the the javascript object-properties (here ID and Quantity) do have the same name and the same type (in this case number == int) as the parameter of your webservice 2.) do not wrap the object into a Data Transfer Object (DTO), but instead just stringify them Thanks goes to Yasin Tarim which gave the hints i needed to get it working

// javascript object
var cartItem = {"ID": 123, "Quantity": 2}

$.ajax({
    type: "POST",
    url: "/WebServices/BasketServices.asmx/AddItemToBasket",
    data: JSON.stringify(cartItem),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) { OnSuccess(cartItem, data); },
});
    // ASMX Server Side Code
    [WebMethod(Description = "Add item to ShoppingCart")]
    [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]        
    public string AddItemToBasket(int ID, int Quantity) 
    {            
        CartItem cI = new CartItem();
        cI.iD = ID;
        cI.qty = Quantity;
        CartItem.SaveToDatabase(ci);
        return "foo from Webservice - it worked";
    }
surfmuggle
  • 5,527
  • 7
  • 48
  • 77
  • "No parameterless constructor defined for type" and "Invalid JSON primitive" and "Invalid web service call, missing value for parameter" were the error messages i received in my various combinations. – surfmuggle Jun 28 '11 at 20:31
  • Yes this worked for me as well... I had to add on server side code each variable by type and name otherwise it doesn't work.. At least not for me, so each variable you have in your json string needs to be on back end as well. – IamCavic Sep 08 '17 at 15:59
2

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 S
  • 23,637
  • 2
  • 63
  • 78
  • I have been looking for this for 4 hours now. Why couldn't JSON.stringify add this based on the javascript variable name? – terjetyl Apr 21 '11 at 22:13
0

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

slf
  • 22,595
  • 11
  • 77
  • 101