5

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!

3
  • i am not sure if that is the reason, you could give the property name as data. data:{ 'firstname': 'brian', 'lastname': 'lee' } Commented Nov 25, 2013 at 5:14
  • stackoverflow.com/questions/16910982/…. i guess you need to get rid of the webmethod.as per this post, webmethods are obsolete Commented Nov 25, 2013 at 5:26
  • I am using ASP.NET, not ASP MVC..:) Commented Nov 25, 2013 at 5:34

1 Answer 1

5

WebMethods 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 ScriptMethods 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);
    }
Sign up to request clarification or add additional context in comments.

2 Comments

You said WebMethods by default respond to POST rather than GET requests.. So how can i set WebMethod respond to GET?
@IswantoSan It is possible, though with some caveats. See my edit.

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.