In MVC, why does returning Content
sometimes fail in the Ajax callback, while returning Json works, even for simple string objects?
Even when it fails, the data is still available if you were to access it in the always callback...
When I set the contentType in the ajax call to text/xml
the response will no longer enter the error message.
$.ajax({
cache: false,
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: 'json',
url: "/MyController/GetFooString",
data: { },
success: function (data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Ajax Failed!!!");
}
}); // end ajax call
Even when it fails, the data is still available.
public ActionResult GetFooString()
{
String Foo = "This is my foo string.";
return Content(Foo);
} // end GetFooString
public ActionResult GetFooString()
{
String Foo = "This is my foo string.";
return Json(Foo, JsonRequestBehavior.AllowGet);
} // end GetFooString
Using Content(Foo);
sends a response that doesn't have the mime type header. This happens because you're not setting ContentType
when using this overload. When the Content-Type is not set, jQuery will try to guess the content type. When that happens, whether it can successfully guess or not depends on the actual content and underlying browser. See here:
dataType (default: Intelligent Guess (xml, json, script, or html))
Json(...)
on the other hand explicitly sets the content type to "application/json"
so jQuery knows exactly what to treat the content as.
You can get consistent result from Content
if you use the 2nd overload and specify a ContentType:
return Content(Foo, "application/json"); // or "application/xml" if you're sending XML
But if you're always dealing with JSON, then prefer using JsonResult
return Json(Foo, JsonRequestBehavior.AllowGet);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With