1

I set up a page method and am trying to call it through jQuery. Sometimes I get to the success function and sometimes to the error function, seems random to me. In any case, the response contains the entire page mark-up.

I tried using both $.ajax and ScriptManager with same results. I also tried the idea here: Call ASP.NET PageMethod/WebMethod with jQuery - returns whole page and nothing.

Here is the JavaScript code:

$(document).ready(function() {
    $(".tree").dynatree({
        onActivate: function(node) {
            $('#title').val(node.data.title);
            $.ajax({
                type: "POST",
                url: window.location.href + "/GetData",
                data: "{'ID':22}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(response) { alert(response); },
                error: function() { alert('Error!'); }
            });
        }
    });
});

And here is the c# code:

[WebMethod]
public static string GetData(string ID)
{
    if (string.IsNullOrEmpty(ID))
        throw new Exception("No ID passed!");
    return "Test";
}

Edit: Well I got it working. I changed the parameter type from int to string and now the method is called. I can just do int.Parse later, but why does this even happen?

Community
  • 1
  • 1
Elad Lachmi
  • 10,406
  • 13
  • 71
  • 133

2 Answers2

1

What's happening is that setting data to {} in the jQuery call is the JSON equivalent of setting it to NULL. In that case, there is no webmethod that accepts null and the call fails.

Lester
  • 4,243
  • 2
  • 27
  • 31
  • Sorry. I updated the post with the correct version (with the parameter) – Elad Lachmi May 19 '11 at 13:24
  • Your answer pointed me in the right direction. Before I had: data: "{'ID':'22'}", so asp.net was looking for a method with parameter type string. Once I removed the ' - everything started working. Thank you! – Elad Lachmi May 19 '11 at 13:58
  • Ah that makes sense. Glad to be of help. – Lester May 19 '11 at 14:06
0

I'm doing something very similar in my current app and the only difference I can see is that i have the following extra option in my ajax call :

beforeSend: function(xhr) { xhr.setRequestHeader("Content-type", "application/json; charset=utf-8"); }

Hope that helps...

ShaneBlake
  • 11,056
  • 2
  • 26
  • 43