-1

I have a simple Razor page and I'm trying to display a button which when clicked will execute a method in the page model code behind, similar to C#'s WPF button. I don't want to use any javascript at all.

I've gotten to a point where it kinda does what I want it to but on page load it executes the method for each element in the for each list. This is something I don't want, I just want the method to be executed on button press.

The razor page code with the for loop is as follows:

    @foreach (var item in @Model.UserData)
{

    <tr>
        <td>@item.Owner</td>
        <td>@item.InputPath</td>
        <td>@item.OutputPath</td>
        <td>@item.Status</td>
        <td>
            <form asp-action="@Model.DownloadCsv(@item.OutputPath)" method="post">
                <button>Download</button>
            </form>
        </td>

    </tr>
    <tr>
        <td colspan="5"> <hr /> </td>
    </tr>
}

In the code behind I just have this right now:

        public IActionResult DownloadCsv(string inputPath)
    {
        int i = 0;
        return Page();
    }
A.A
  • 743
  • 1
  • 8
  • 20
  • That is not how razor works. You a confusing client-side and server-side concerns. – Nkosi Aug 11 '19 at 16:24
  • What would the correct way of doing it then? I'm completely new to asp.net. – A.A Aug 11 '19 at 16:27
  • 1
    Take a look here https://learn.microsoft.com/en-us/aspnet/core/razor-pages/?view=aspnetcore-2.2&tabs=visual-studio#multiple-handlers-per-page – Nkosi Aug 11 '19 at 16:33
  • I noticed it appends the url with the method name, is there a way to prevent this? It makes it annoying if you refresh teh page. – A.A Aug 11 '19 at 16:44
  • Yes, it does, and the solution is to read the docs (link provided by Nkosi). They are very clear with how one should setup it all up. – Asons Aug 11 '19 at 17:45

1 Answers1

1

You could use asp-page-handler to select handler and asp-route-{attribute} to pass the parameter.And use return File() to download the file without page refreshing.

Page:

@page 
...
<td>
    <form method="post">
        <button type="submit" asp-page-handler="DownloadCsv" asp-route-inputPath="@item.OutputPath"
                class="btn btn-success">
            Download
        </button>
    </form>
</td>

PageModel:

public ActionResult OnPostDownloadCsvAsync(string inputPath)
    {
       //other logic
        return File("path\to\file", "application/octet-stream",
                    "DownloadFileName.csv");
    }

Refer to

Download file to browser using .NET Core Razor Pages

Return PDF to the Browser using Asp.net core

Ryan
  • 19,118
  • 10
  • 37
  • 53