Downloading a CSV file from MVC Controller

So I had a request from a user on an app to download a CSV file from my MVC web site.  I had previously showed how to upload a csv to MVC, so this shouldn't be hard.  The first thing you need to do is create a function on your controller to put the file together and return it.  Here is a really simple example.  
    public FileContentResult DownloadCSV()
    {
        string csv = "Charlie, Chaplin, Chuckles";
        return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "Report123.csv");
    }
Since CSV is just a text file, I put together a really simple one there to get the idea across.  All that is special about this function is that it returns a FileContentResult vs ActionResult (though that probably would be fine) and return a File.  That was reason.  Now the link http://site/App/controller/DownloadCSV should return a file.  You just need to create a link in your front end and done.  
If you want to do all of this from a JQuery call, it would look something like this.

$.ajax({
    type: 'POST',
    url: '/Controller/DownloadCSV', 
    data: '{  }',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (returnValue) {
        window.location = '/Reports/Download?file=' + returnValue;
    }
});

Add comment