0

I'm running a web service with a test method (rename file). With Ajax(client side) I'm able to call the function on my service.

But when I'm sending an Int, String..or whatever to my method, the data shows "null"; What's the problem ?

my javascript:

 
$.ajax({
    url: "WebServiceTest.asmx/NewId",
    type: "POST",
    contentType: "application/json; charset=utf-8",
    //data: JSON.stringify({ rename: newName}),
    data: "{ 'Id': 8 }",
    dataType: "json",
    success: function(data) {
        alert(data.d);
    }
});

my webservice

[System.Web.Script.Services.ScriptService]
public class WebServiceTest: WebService
{

    [WebMethod]
    public int NewId(int id )
    {
        //..do something

        return id; //always null
    }        
}

Thank you ! :)

Maurits van Beusekom
  • 5,579
  • 3
  • 21
  • 35
  • 1
    This could be a casing issue, have you tried updating the `Id` parameter of the JSON message to lower case? The parameter name of the webservice method is defined in lowercase however in the JSON message it starts with a capital "I". Maybe try with the following JSON message `{ 'id': 8 }`. – Maurits van Beusekom Feb 25 '20 at 14:22

2 Answers2

1

ASMX Web Services use SOAP, so you need to send your messages inside a SOAP payload. Try to send your message like this:

data: '<soap:envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
  '<soap:body>' +
  '<newid xmlns="WebServiceTest.asmx/NewId">' +
  '<id>' + id + '</id>' +
  '</newid>' +
  '</soap:body>' +
  '</soap:envelope>',
beforeSend: function (xhr) {
  xhr.setRequestHeader('SOAPAction', 'WebServiceTest.asmx/NewId');
},
Ricardo Peres
  • 13,724
  • 5
  • 57
  • 74
  • ASMX web services can also be called with `HttpPost`, so you don't need to use only SOAP. [Enable ASP.NET ASMX web service for HTTP POST / GET requests](https://stackoverflow.com/questions/618900/enable-asp-net-asmx-web-service-for-http-post-get-requests) – Selim Yildiz Feb 26 '20 at 10:19
  • How is that related to SOAP? This answer is about the GET verb. – Ricardo Peres Feb 26 '20 at 10:29
0

The parameters of Http requests are case-sensitive . So that as @Maurits van Beusekom pointed on comment, it seems you are not sending data properly: data should be data: "{ 'id': 8 }" instead of data: "{ 'Id': 8 }" as follow:

 $.ajax({
    url: "WebServiceTest.asmx/NewId",
    type: "POST",
    contentType: "application/json; charset=utf-8",
    data: "{ 'id': 8 }",
    dataType: "json",
    success: function (data) {
        alert(data.d);
    }
});
Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28