views:

39

answers:

3

I have stripped my getJSON call to the simplest example possible trying to figure out why it's not working but I'm out of ideas. I currently have:

public JsonResult MyAction()
{
    return Json(new { status = "OK" });
}

$.getJSON('MyController/MyAction', function(result) { alert('worked'); });

The action is called, but the alert does not get fired and looking in Chrome developer tools I see a Status 500 error code is returned. What can possibly be causing this? How can I debug it?

A: 

Pls, use firebug (or fiddler) in the Network tab, choose XHR, to see what you send and receive.

As Michael Shimmins says, MVC 2 blocks Get requests by default, because of Json Hijacking. Here is an interesting article:

http://www.ifunky.net/blog/post/AspNet-MVC-2-JsonRequestBehaviorAllowGet.aspx

They talk here about this message: "This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request."

netadictos
I've edited my answer
netadictos
+6  A: 

By default MVC 2.0 blocks GET requests to actions that return a JsonResult.

Use JsonRequestBehavior.AllowGet to force the issue, or use POST.

public JsonResult MyAction()
{
    return Json(new { status = "OK" }, JsonRequestBehavior.AllowGet);
}

Or use post:

$.post('MyController/MyAction', function(result) {
    alert('worked');
});
Michael Shimmins
This is so annoying. I seem to periodically forget this every few months and waste another few hours trying to figure it out. Thanks for the `post` suggestion as well, it's probably the only jQuery ajax call I haven't ever used.
fearofawhackplanet
A: 

I think that MyController/MyAction is relative to whatever url you are now. try 'MyController/MyAction'.

EDIT: Also try to call MyController/MyAction from whichever url you are currently and check that it returns the desired result

EDIT: Actually thats not the problem. As Michael pointed out this would return a 404 error.

Yannis
That would return an error 404, not 500.
Michael Shimmins
Correct - I will edit...
Yannis