Stop IE From Displaying a File Download dialog when returning JSON
It’s a common problem… you write a simple action on your controller that returns JSON, but when you perform the AJAX call – you get a “File Download” dialog box when using IE (note – this could happen in other browsers as well, but for this specific issue, FF and Chrome worked fine). What’s not so common, are the many solutions – caused by the many different errors that can cause this problem.
Here’s the simple action method that I am calling:
public JsonResult Register(string name, string email, int locationId)
{
var msg = string.Empty;
var status = "success";
//do stuff….
return Json(new { Status = status });
}
The following jQuery code is used to collect, encode, send and process the AJAX request:
$(".submit").click(function() {
$.ajax({
type: "POST",
url: "/member/register",
data: $("#subscribeForm").serialize(),
dataType: "json",
success: function (result) {
if (result.Status == "success") {
flashSuccess(result.Message);
$("#email").val("Enter Your Email Address");
$("#name").val("Your Name");
} else {
flashError(result.Message);
}
},
error: function (req, status, error) {
flashError("There was a problem registering your email, please try again.");
}
});
return false;
});
As I said above, this code worked fine in Firefox and Chrome, but IE would always display a File Download box. It turns out that you need to be a little more explicit for IE – so simply adding the bolded line below fixed the problem:
$(".submit").click(function() {
$.ajax({
type: "POST",
url: "/member/register",
data: $("#subscribeForm").serialize(),
dataType: "json",
contentType: "application/x-www-form-urlencoded;charset=utf-8",
success: function (result) {
if (result.Status == "success") {
flashSuccess(result.Message);
$("#email").val("Enter Your Email Address");
$("#name").val("Your Name");
} else {
flashError(result.Message);
}
},
error: function (req, status, error) {
flashError("There was a problem registering your email, please try again.");
}
});
return false;
});
That’s it! Hope that helps.
