I am submitting a form in Razor Pages. OnPost method creates a MemoryStream and returns the data as a file. However after this, I would like to take the user to a page that says "Thank you for using this service to create your file". Since "Return File" is the very last thing the OnPost method does, I can not change the page after. Any help is appreciated.
public ActionResult OnPost()
{
this.date = Request.Form["date"];
this.name = Request.Form["name"];
this.lastname = Request.Form["lastname"];
string filename = "HelloWorld.docx";
string contenttype = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
var stream = new MemoryStream();
// **************************
// Creating the document here
// **************************
return File(stream, contenttype, filename);
}
The word document is created fine and downloaded without any problem. I can’t change the page after though.Can I perhaps download the file without return, so that I can use "RedirectToPage" after?
I tried submitting the form to another page. However, the OnPost method of the other page is executed without actually displaying its front end. It just downloads the file from the back end of the other page.
2
Answers
Thank you Dave B for giving the idea to use two different pages. That helped. I did solve it a bit differently though.
In the first page I have created a parameter. If it is not set, it displays the form. Therefore, in the first access, it always displays the form.
Then when the submit button is clicked, OnPost saves the form data to TempData and sets the variable. This triggers the first page to display the thank you message instead of the form.
Then JavaScript redirects the URL to the second page which in OnGet method creates the word file and returns it.
I’ve expanded my comments in your original question with a full sample. This sample follows the sequence used by Microsoft.com when selecting a version of Visual Studio to download: Select the version to download; the browser is directed to the "Thank you for downloading Visual Studio" and the file is downloaded after page load.
OnPost()
method of the Razor page with the form.Razor page with form named ‘FormBeforeThankYou’
.cshtml
.cshtml.cs
DOMContentLoaded
document event and executingwindow.open(url, '_self');
in the event listener function. Note the format of the URL"/ThankYouDownload?handler=Download";
. It’s requesting theOnGetDownload()
method.Razor page with "thank you" message and automatic file download named ‘ThankYouDownload’
.cshtml
.cshtml.cs