MVC Controller Return Content vs Return Json Ajax

In MVC, why does returning Content sometimes fail in an Ajax callback, returning Json, even for simple string objects?

Even when this fails, the data is still available if you want to access it in the always callback ...

Update:

When I set contentType in an ajax call to text/xml , the response will no longer introduce an 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, 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 
+8
json jquery c # ajax asp.net-mvc
source share
1 answer

Using Content(Foo); sends a response that does not have a header of type mime. This is because you are not setting ContentType when using this overload. When Content-Type is not set, jQuery will try to guess the type of content. When this happens, whether it can successfully guess or not depends on the actual content and the 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 content as.

You can get a consistent result from Content if you use the second overload and specify ContentType:

 return Content(Foo, "application/json"); // or "application/xml" if you're sending XML 

But if you always deal with JSON, then you prefer to use JsonResult

 return Json(Foo, JsonRequestBehavior.AllowGet); 
+14
source share

All Articles