LoginSignup
2
0

More than 5 years have passed since last update.

ASP.NET Core の Razor ページでダウンロードを実装したい

Last updated at Posted at 2019-04-10

Bootstrap ガチガチなサイトに、ポツンと Excel ファイルのダウンロードボタンを設置したい!

ASP.NET Core MVC では Controller に介入すれば良いが、Razor ページではどうだったか…

Razor ページの変更

Problems.cshtml の方にダウンロードのリンクを設置します。

  <a asp-page="/Problems" asp-page-handler="Download">Excel</a>

asp-page-handler="Download" のように追加します。Download 以外でも良いです。

詳細につきましては ASP.NET Core のアンカー タグ ヘルパー を参照してください。

ページ モデルの修正

OnGetHandlerAsync メソッドを追加します。Handler の部分を先ほどの Download に変更して、
OnGetDownloadAsync メソッドを書きます。

  public IActionResult OnGetDownloadAsync()
  {
    return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "File.xlsx");
  }

Razor ページに設置したハイパーリンクは、
<a asp-page="/Problems" asp-page-handler="Download">Excel</a>

つぎのようになっていました。
<a href="/~/Problems?handler=Download">Excel</a>

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0