I am trying to achieve exactly what the poster in this question is trying to do except the browser (Chrome) doesn't attempt to download the .csv file or present the user with a download box. I am using a HTTP GET request and the code is virtually identical in the question above. I'm using Fiddler to monitor the traffic and I can see the .csv file stream in the response, but the browser seems to be ignore it and I can't work out why...
Here is my current implemenation (base on @MattThrower's question):
I make an AJAX call to the MVC controller:
$("#exportToCsvLink").click(function () {
$.ajax({
type: "GET",
url: window.project.common.routes.urls.ExportChartDataToCsv,
data: { parameterId: parameter.parameterId }
});
});
The MVC controller processes the CSV export and returns a FileStreamResult
public FileStreamResult ExportChartDataToCsv(int parameterId)
{
List<TestViewModel> data = _CommonService.GetData(parameterId);
var result = WriteCsvToMemory(data);
var memoryStream = new MemoryStream(result);
return new FileStreamResult(memoryStream, "text/csv") { FileDownloadName = "export.csv" };
}
public byte[] WriteCsvToMemory(IEnumerable<TestViewModel> data)
{
using (var memoryStream = new MemoryStream())
using (var streamWriter = new StreamWriter(memoryStream))
using (var csvWriter = new CsvWriter(streamWriter))
{
csvWriter.WriteRecords(data);
streamWriter.Flush();
return memoryStream.ToArray();
}
}