Coup123
Coup123

Reputation: 1

AJAX Post data to asmx WebService Method always null

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 ! :)

Upvotes: 0

Views: 426

Answers (2)

Selim Yildiz
Selim Yildiz

Reputation: 5370

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);
    }
});

Upvotes: 0

Ricardo Peres
Ricardo Peres

Reputation: 14535

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');
},

Upvotes: 1

Related Questions