Share via


MVC return file(download pdf) then redirect to another action on submit button.

Question

Monday, September 3, 2018 6:45 AM

Good day.

I have a view where the user will click a button on a modal then it will download a pdf file of the filled-up form. I wanted it to download the pdf then redirect it to another view.
I tried adding onbuttonclick function so that when the user clicks  the submit button, it should redirect to other page but unfortunately it didn't work.

What is the best method to solve this? Thanks.

View

<input type="submit" value="Submit" class="btn btn-success col-lg-2" />

Controller

Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/pdf", "ApplicationForm.pdf");

If I add another return RedirectToAction(), it shows an error. 

I also tried doing this

    function PostOther() {
        if (confirm("Form Downloading. Please wait."))
            window.location.href = "@Url.Action("Index", "Application")";
        else
            return false;
    }

wherein when the user click ok in the alert box, this should trigger the window.location.href unfortunately, it only loads the pdf file and not redirect to the assigned page.

Thanks in advance.

All replies (8)

Monday, September 3, 2018 3:33 PM ✅Answered

The server can only return one response. If you return a file, the page gets no response. This means client code will need to do the redirect after it’s requested the download.


Wednesday, September 5, 2018 9:25 AM ✅Answered

You can initiate the download from client script as Bruce said, and then redirect: https://stackoverflow.com/questions/6894900/download-a-file-via-jquery-and-redirect


Monday, September 3, 2018 8:01 AM

i think you need something like this in your function :

window.location.href = "/Application/Index";

Tuesday, September 4, 2018 5:10 AM

The server can only return one response. If you return a file, the page gets no response. This means client code will need to do the redirect after it’s requested the download.

How will I be able to do this? After loading of page, it only downloads the file then stops there. Thanks


Tuesday, September 4, 2018 8:47 AM

Hi mrveeen,

If redirect to another page in controller,you could use return Redirect().

But it only run one action which return file() after submitting.

The action also doesn't return back to the view.

So I don't think you can do this.

Best Regards.

Yuki Tao


Tuesday, September 4, 2018 8:51 AM

But it only run one action which return file() after submitting.

So there is no possible way to do this? Thanks Sir.


Tuesday, September 4, 2018 12:05 PM

Downloading of File is stateless means server will never know whether File has downloaded or cancelled or Failed.

Thus whatever you are trying to do is not possible.


Wednesday, September 5, 2018 1:28 AM

Thus whatever you are trying to do is not possible.

Thanks sr.