Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Controller Return Content vs Return Json Ajax

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...

Update:

When I set the contentType in the ajax call to text/xml the response will no longer enter the error message.

AJAX:

$.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

Controller Action That Fails (Sometimes)

Even when it fails, the data is still available.

public ActionResult GetFooString()
{
    String Foo = "This is my foo string.";
    return Content(Foo);
} // end GetFooString

Controller Action That Always Works

public ActionResult GetFooString()
{
    String Foo = "This is my foo string.";
    return Json(Foo, JsonRequestBehavior.AllowGet);
} // end GetFooString
like image 234
silencedmessage Avatar asked Sep 22 '14 20:09

silencedmessage


1 Answers

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); 
like image 180
Mrchief Avatar answered Oct 17 '22 23:10

Mrchief