POST JSON data to .asmx webservice

24,679

Solution 1

Make sure your ASMX service class is decorated with the [ScriptService] attribute.

Solution 2

You should use as data the value which formatted as correct JSON data:

{"myparm1":105,"myparm2":23}

instead of

{myparm1:105,myparm2:23}

You can validate on the site http://www.jsonlint.com/ which data are JSON data. So you should change your code to

$.ajax({
    type: 'POST',
    url: "http://localhost/WebServices/MyTest.asmx/JsonTest2",
    data: '{"myparm1":105,"myparm2":23}',
    contentType: 'application/json; charset=UTF-8',
    dataType: 'json',
    async: false,
    success: function (msg) {
        alert(msg.d);
    },
    error: function (msg) {
        alert('failure');
        alert(msg);
    }
});

In case of more complex input parameters I recommend you to use JSON.stringify functionfrom the json2.js (see this answer for example):

var myValue1 = 105, myValue2 = 23;
$.ajax({
    type: 'POST',
    data: JSON.stringify({myparm1:myValue1, myparm2:myValue2}),
    ...
});

In the last version of $.ajax usage the myValue1 and myValue2 can be complex structures (objects with properties) or arrays having even another complex structures or arrays as the properties.

Share:
24,679
swandog
Author by

swandog

Updated on July 10, 2020

Comments

  • swandog
    swandog almost 4 years

    I'm trying to post some simple parameters to a .asmx webservice.
    I get the following error: Request format is invalid: application/json; charset=utf-8.
    What I really need to get to is to be able to pass a complex object, but I can't get past making a POST request with json content type.

    Here is my WebService Definition

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public int JsonTest2(int myparm1, int myparm2)
    {
        return 101;
    }
    

    And this is my javascript code

    function JsonTest2() {
        $.ajax({
            type: 'POST',
            url: "http://localhost/WebServices/MyTest.asmx/JsonTest2",
            data: "{myparm1:105,myparm2:23}",
            contentType: 'application/json; charset=UTF-8',
            dataType: 'json',
            async: false,
            success: function (msg) {
                alert(msg);
            },
            error: function (msg) {
                alert('failure');
                alert(msg);
            }
        });
    }
    
  • LCJ
    LCJ almost 10 years
    It would be good if you mention the minimum .Net version needed for this.