1

I have a method in a controller to return a FileResult:

public FileResult DownloadRequestsAsCsvFile()
{   
    var contentType = "text/csv";
    var content = CreateCsvFileOfPendingLeadRequests();
    var bytes = Encoding.UTF8.GetBytes(content);
    var result = new FileContentResult(bytes, contentType);
    string n = string.Format("LeadRequests-{0:yyyy-MM-dd_hh-mm-ss-tt}.csv", DateTime.Now);
    result.FileDownloadName = n;
    return result
 }

I have a knockout function to call the controller method to download the file, the method gets called and the method is completed but the file is not downloaded using the browser. How do I get the browser to download the file?

self.getCsvFileOfRequests = function () {
            $.get('../Home/DownloadRequestsAsCsvFile', function (csv) {

            }).done(function() {
                toastr.success("File downloaded successfully.")
            }).error(function() {
                toastr.error("There was a problem downloading the file.");
            });
        }
Jonathan Kittell
  • 7,163
  • 15
  • 50
  • 93

2 Answers2

2

You can't really download files with jQuery this way. What you have to do, is inject a hidden iframe into your DOM, and set its source url to the url of the file you want to download. See this answer for more info.

Community
  • 1
  • 1
Tobias
  • 2,811
  • 2
  • 20
  • 31
1

I would just make it an anchor link. The browser will handle the rest.

Ahuman
  • 752
  • 6
  • 18