8

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);
        }
    });
}
1
  • 2
    which asp.net version are you using? shouldn't there be a msg.d in the success callback? Commented Mar 16, 2011 at 4:00

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

It would be good if you mention the minimum .Net version needed for this.
3

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.

Comments

0

Make sure the URL contains port number when using localhost.

  url: "http://localhost:1297/WebServices/MyTest.asmx/JsonTest2",

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.