jQuery.getJSON Call ASP.NET method

asp.net, jquery, json

Solution

`WebMethod`s by default respond to `POST` rather than `GET` requests.

$.ajax({
    type: 'POST',
    url: 'Default2.aspx/GetPerson',
    dataType: 'json',
    // ...
});

And, the request format should be JSON as well to match the `ResponseFormat`:

// ...
    data: JSON.stringify({ 'firstname': 'brian', 'lastname': 'lee' }),
    contentType: 'application/json'

Alternatively, a `ScriptMethod` can be configured to use `GET` instead:

[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]

Though, `contentType` still needs to be set for it, so `$.getJSON()` can't be used:

$.ajax({
    type: 'GET',
    url: 'Default2.aspx/GetPerson',
    dataType: 'json',
    contentType: 'application/json',
    // ...
});

And, `data` will be URL-encoded, but each value will need to be JSON-encoded before that:

// ...
    data: {
        firstname: JSON.stringify('brian'),
        lastname: JSON.stringify('lee')
    }

Also note that `ScriptMethod`s will wrap their response in a `{ "d": ... }` object. And, since the `return` value is a `String`, the value of `"d"` be that same unparsed `String`:

// ...
    success: function (response) {
        response = JSON.parse(response.d);
        alert(response.Age);
    }

Problem

I have jQuery code to get JSON from the server: ``` $(document).ready(function () { $.getJSON('Default2.aspx/GetPerson', { 'firstname': 'brian', 'lastname': 'lee' }, function (response) { alert(response.Age); }); }); ``` Default2.aspx code : ``` [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public static String GetPerson(String firstname, String lastname) { Person p = new Person(firstname, lastname); return "{\"Age\":\"12\"}"; } ``` The question is : Why `GetPerson` method is not called from my script? I attach the debugger in `GetPerson` but it seems doesn't called. Any help would be appreciate!

Original source