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");
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With