I have something like this in my View:
var url = '@Url.Action("DownloadZip", "Program")' + '?programNums=' + selectedRow;
$.ajax({
url: url,
dataType: 'json',
async: false,
success: function (data) {
if (data != "Successful") {
alert(data);
}
}
});
The controller can return a File or can return a JSON result if there was an error.
Haven’t been able to get them both work together.
Here is what it looks like:
public ActionResult DownloadZip(string programNums)
{
if(string.IsNullOrEmpty(programNums))
{
return Json("Error, blank info sent.", JsonRequestBehavior.AllowGet);
}
var memoryStream = new MemoryStream();
using (var zip = new ZipFile())
{
zip.AddFile("C:\\sitemap.txt");
zip.Save(memoryStream);
}
memoryStream.Seek(0, 0);
return File(memoryStream, "application/octet-stream", "archive.zip");
}
What I am seeing is that the ajax call needs a JSON value back. Since in my case, it returns a File, it cannot work. Anyway to handle what I am doing to where it can give back a JSON or a File from the ajax call.
Have you considered passing back JSON with a file Url?
If the file is successfully found/created. Send back a JSON result with the link to the file. Then in javascript use
windows.locationto retrieve the file. When there is an error, the JSON result will contain the error information and this info can be displayed to the user. For this to work, you’ll need to create another endpoint (action) that can stream the file.