Question

I have a link on a page and I'd like a "open or save csv file" dialog to appear when the user clicks on the link. The link points to an action method in which I generate a string representing valid CSV output. The only thing I don't know how to do is output a file that the user can open or save. I think I might have to do something about changing the http headers or something like that but I'm not too sure.

Please help. It'll make the difference between getting home at a reasonable time on a Friday evening or not. ;-).

Was it helpful?

Solution

Return as FileContentResult and put MIME type as "text/csv".

public FileContentResult Download()
{
    string csvContent = "field1,field2,field3";
    var data = Encoding.UTF8.GetBytes(csvContent);
    string filename = "Simple.csv";
    string mime = "text/csv";
    return File(data, mime, filename);
}

In the view page, simply creat a link to prompt for download.

@Html.ActionLink("Download File", "Download")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top