4

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();
    }
}
Community
  • 1
  • 1
Mark Erasmus
  • 2,305
  • 6
  • 25
  • 37
  • Just use an ActionLink, and no ajax ? see http://stackoverflow.com/questions/9897666/return-pdf-in-ajax-request – Raphaël Althaus Jun 19 '14 at 14:53
  • @RaphaëlAlthaus that works. The other post suggested this was possible via an AJAX call. A normal ActionLink will suffice for my needs. Thanks, post as answer and I will accept. – Mark Erasmus Jun 19 '14 at 15:19

0 Answers0