If I have an AJAX call that returns, say, a CSV, how do I get the browser to prompt the user for a download? Below, the ProductsExport will return the CSV in the success data. I just need what I’d replace the // Deliver file to user line with…
$.ajax({
type: "POST",
url: "/Search/ProductsExport",
data: $('#CustomerId').serialize(),
success: function (data) {
// Deliver file to user!!
},
error: function (xhr, textstatus, errorThrown) {
alert('Error');
}
})
My C# code on the back end looks like so:
var aFileContent = Encoding.ASCII.GetBytes(export);
var aMemoryStream = new MemoryStream(aFileContent);
return File(aMemoryStream, "text/plain",
string.Format("{0}.csv", CustomerId));
You cannot as far as I’m aware. You can’t use ajax here as a file download.
YEs – its a support datatype as per jQuery but not for a file. You need to link to the file for a non ajax request either via a link or a jQuery get request.
See:
Unable to open download save dialog
and
“datatype” on
http://api.jquery.com/jQuery.ajax/