ASP.NET MVC: Internal Server Error (500) on Action Method Returning Json Result


The ASP.NET MVC framework allows you to easily return Json from an action method. This makes jQuery Ajax calls very easy to implement, as shown below.

The JavaScript

$(.button).getJSON('/Home/GetJsonData', 
                   { id = 34 },
                   function(data) {
                      // Do something with it
                   }
);

The Action Method

public ActionResult GetJsonData(int id)
{
     Person person = this.personService.GetPerson(id);     
     return Json(person);
}

There is only one problem with the above action method. If you attempt to run it, the call to the ActionMethod will result in a Internal Server Error (Error 500). The reason is that by default data can only be retrieved using a POST operation if your action method returns a Json result. To make this work with a GET request, all you need to use is the overloaded Json() method shown below.

public ActionResult GetJsonData(int id)
{
     Person person = this.personService.GetPerson(id);     
     return Json(person, JsonRequestBehavior.AllowGet);
}
Follow

Get every new post delivered to your Inbox.

Join 69 other followers