1
votes

I have a form in one of my razor-pages which when submitted, will generate a byte[] and the I return a FileStreamResult. The problem is, all that happens is the page refreshes and I'm not prompted to download a file.

Here's my form:

<form autocomplete="off" method="post" asp-page-handler="attendance" asp-route-id="@Model.Data.Id">
    <div class="form-group">
        <label class="font-weight-bold">Date of meeting</label>
        <input class="form-control datepicker" id="meeting-date" type="text" value="DateOfMeeting" />
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-primary btn-block">Download document</button>
    </div>
</form>

And this is my page handler:

public async Task<IActionResult> OnPostAttendanceAsync(int id) 
{
    var query = new AttendanceList.Query {
        Date = DateOfMeeting,
        SchoolId = id
    };

    var model = await _mediator.Send(query);

    var stream = new MemoryStream(model.Data);

    return new FileStreamResult(stream, ContentType.Pdf) {
        FileDownloadName = "Attendance.pdf"
    };
}

I don't understand what I'm missing here.

Edit: The handler is being called successfully. If I put a breakpoint in and debug, the handler completes successfully, but no file sent to the browser.

1
Maybe the tag-helpers aren't being imported. What's the URL look like for the form in your browser's dev tools?serpent5
@KirkLarkin This is the URL for the form: action="/Schools/Details/44?handler=attendance". If I debug, the handler is being called correctly and it hits the breakpoint and the method completes without any exceptions.Jason Goodwin
FWIW, there's no point in returning a stream when you already have a byte[] in memory. All you're doing is doubling the memory usage. Just return FileResult with the byte[] directly.Chris Pratt
You need to return FileContentResult.Tom Pickles

1 Answers

1
votes

Ok so the issue lies with using POST instead of GET as the form method.

I have updated the code to the following and the download prompt now appears and all is well:

<form autocomplete="off" method="get" asp-route-id="@Model.Data.Id">
    <input type="hidden" name="handler" value="attendance" />
    <div class="form-group">
        <label class="font-weight-bold">Date of meeting</label>
        <input class="form-control datepicker" type="text" name="dateOfMeeting" />
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-primary btn-block">Download document</button>
    </div>
</form>

And the handler signature is now:

public async Task<IActionResult> OnGetAttendanceAsync(int id, string dateOfMeeting)