In my current MVC application I perform an AJAX call to the controller. The controller gets an object from the database and returns it in the form of a JSON response. My confusion is between using the Controller.Json method vs JavaScriptSerializer.Serialize(object). My object I am converting is a simple class called PhoneSerializable with a few public properties of type string and int.
I have the following:
var serializedPhone = jsSerializer.Serialize(new PhoneSerializable(phone));
return new ContentResult {Content = serializedPhone, ContentType = "application/json"};
This works correctly and I get a JSON response that my AJAX caller can parse. Yet some online examples I have seen use this instead:
return Json(new PhoneSerializable(phone));
The response of this has mostly null properties and a DenyGet header which means it failed parsing or something. The documentation for the Json(object) method states that it uses the same javascript serializer for the object yet it fails to convert my simple object to JSON.
What am I missing? I would like to use Json(object) since it is much cleaner but I cannot seem to get it to work.
EDIT WITH ANSWER:
The Json() method was defaulting to "DenyGet" adding more parameters fixed the issue and it now works:
return Json(new PhoneSerializable(phone),
"application/json",
JsonRequestBehavior.AllowGet);