0

I need to retrieve JSON or HTML from my MVC controller by an Ajax call. The question is why that below doesn't work with a GET request ?

$.ajax({
    url: url,
    type: "POST", //It works but doesn't work with GET 
    success: function (data) {
        ...
    }
});

public ActionResult Index()
{
       if (User.Identity.IsAuthenticated)
       {
              ...
              return View(selectedUser);
        }
        return Json(new { Error = Messages.AUTHENTICATIONEXPIRED });
}

With HTTP GET it get nothing instead the Json Object. The Action method is executed successfully. Is there a technical reason that I don't know? is there another way to make it work without making a POST call? Thanks

DevT
  • 1,411
  • 3
  • 16
  • 32
  • What is happening? An error? Try decorating the action method with `[HttpGet]` – Jamie Rees Oct 09 '15 at 09:55
  • What exactly doesn't work when you're trying to get it instead of post? Are you getting exception, 404, anything else? Have you tried to debug server-side, is method you've shown called? Is there a chance this method has been decorated with [POST] attribute in your real code? – Andrey Korneyev Oct 09 '15 at 09:55
  • it just retrieve nothing instead the JSON object. The action is fine, yes sure I debugged it. – DevT Oct 09 '15 at 09:56

1 Answers1

2

When returning Json through GET, you have to add JsonRequestBehavior.AllowGet :

return Json(new { Error = Messages.AUTHENTICATIONEXPIRED }, JsonRequestBehavior.AllowGet);

More info there.

Community
  • 1
  • 1
xlecoustillier
  • 16,183
  • 14
  • 60
  • 85