Using ASP.NET Razor Pages, I am trying download a file to the browser. From the Page(html), using a link like this works fine:
href="/DownloadableFiles/testB.csv" download="newname">Download Link
However, I want to initiate the download from the code-behind or ViewModel so it can be dynamic as to what the filename is, I also need to inspect the file first, etc.
In ASP.NET MVC core, (not RazorPages) you can download a file in code using:
return File(memory, GetContentType(path), Path.GetFileName(path));
But return File is not supported in Razor Pages.
pitaridis is correct, return File exists in Razor Pages, I must have been missing a namespace.
This will download a file from Code Behind:
In the page, here's the submit button:
<button type="submit" asp-page-handler="DownloadFile" style="width:75px"
class="cancel"> Download </button>
In the PageModel (code behind):
public ActionResult OnPostDownloadFile()
{
return File("/DownloadableFiles/TestFile34.csv", "application/octet-stream",
"NewName34.csv");
}
Note: /DownloadableFiles is in a subfolder of wwwroot
It's also possible to use a GET call instead of POST like this:
Put this in your page code behind:
public ActionResult OnGetDownload()
{
return File("c:/Directory/FileName.csv", "application/octet-stream", "FileName.csv");
}
And put this on that page:
<a href="@Url.Page("ThePageName", "Download")>Download</a>
If you want to pass parameters, just include them in the Url.Page call and add parameters to OnGetDownload like this:
public ActionResult OnGetDownload(int Id)
{
return File("c:/Directory/FileName.csv", "application/octet-stream", "FileName.csv");
}
<a href="@Url.Page("ThePageName", "Download", new { Model.Id })">Download</a>
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