Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.net MVC Return File and Redirect

I have a controller that returns csv file. I want to redirect to an action after this has displayed, i.e. return to the home view. The controller logic is shown below:

public ActionResult DownloadCSV(string fileName)
{
    string csv;
    using (StreamReader sr = new StreamReader(fileName))
    {
        csv = sr.ReadToEnd();
    }
    return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "Export.csv");
}
like image 771
Simon Avatar asked Jun 28 '13 11:06

Simon


1 Answers

The short version is that you can't force a file download and redirect in the same action because of HTTP limitations. But you could force the download by opening the file-download action using window.open.

Example:

<a href="Action/RedirectPage" data-file="Action/DownloadCVS" class="file-download">Download File</a>

<script>
  $(function() {
      $('a.file-download').click(function() {
         window.open($(this).data('file'));
      }); 
  });
</script>

In this case I used HTML5 attributes, but you're not limited to do it in this way.

like image 91
Meryovi Avatar answered Nov 15 '22 08:11

Meryovi