skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.

    <!--  1st Page Part - Thank You Message -->
    @if (ViewData["message"] != null)
    {
      Thank you message here 
      <script>
      window.location.href = "./PageToCreateFile";
      </script>
    }
    
    <!--  2nd Page Part - The Form -->
    else
    {
     form data filled here
    }
    

  2. 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.

    1. After successful validation of form data in the post request, redirect to the "thank you" page from the OnPost() method of the Razor page with the form.

    Razor page with form named ‘FormBeforeThankYou’

    enter image description here

    .cshtml

    @page
    @model WebApplication1.Pages.FormBeforeThankYouModel
    @{
    }
    <form method="post">
        <input type="email" name="emailaddress" />
        <button type="submit">Submit</button>
    </form>
    

    .cshtml.cs

    public class FormBeforeThankYouModel : PageModel
    {
        public void OnGet()
        {
        }
    
        public IActionResult OnPost()
        {
            string emailAddress = Request.Form["emailaddress"].ToString();
            
            // TempData reference:
            // https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-8.0#tempdata
            TempData["ValidatedFormData"] = emailAddress;
    
            return RedirectToPage("ThankYouDownload");
        }
    }
    
    1. Trigger the file download from the thank you page. The file download is automatically downloaded by connecting to the DOMContentLoaded document event and executing window.open(url, '_self'); in the event listener function. Note the format of the URL "/ThankYouDownload?handler=Download";. It’s requesting the OnGetDownload() method.

    Razor page with "thank you" message and automatic file download named ‘ThankYouDownload’

    enter image description here

    .cshtml

    @page
    @model WebApplication1.Pages.ThankYouDownloadModel
    @{
    }
    <h1>Thank You</h1>
    <h3>Your file will download automatically.</h3>
    @section Scripts {
        <script>
            document.addEventListener('DOMContentLoaded', downloadFile);
    
            function downloadFile() {
                const url = "/ThankYouDownload?handler=Download";
                // https://stackoverflow.com/questions/54626186/how-to-download-file-with-javascript/64874674#64874674
                window.open(url, '_self');
            }
        </script>
    }
    

    .cshtml.cs

    public class ThankYouDownloadModel : PageModel
    {
        public void OnGet()
        {
        }
    
        public ActionResult OnGetDownload()
        {
            // Process data in TempData
            System.Diagnostics.Debug.WriteLine(TempData["ValidatedFormData"]);
    
            // Generate memory stream
    
            // Return generated stream as a file download
            return File("/assets/sample.txt", "text/plain", "sample-download.txt");
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search