Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In ASP MVC, how can I return a new view AND a file to the user?

Thought I would pose this to the StackOverflow crowd since I've run out of ideas.

I have a request from users that once a button is clicked, a PDF form is generated which they would like to automatically view, and once they close the PDF the page will already be a "Final page", not the page they clicked the button from.

In my pre-final page with the button, the controller calls:

return File(finalForm, "application/pdf", Server.HtmlEncode(finalForm));

But this has now passed the control to the client, I can't route to a different View.

Any clever ideas on how I can also display a new view?

like image 624
Mark Kadlec Avatar asked Jan 22 '23 11:01

Mark Kadlec


2 Answers

I've broken this down into two separate actions on the Home Controller, using the FinalPage action as the view you get redirected to and the GetFile action as the one to return the file itself.

Controller

    public ActionResult GetFile()
    {
        return File(@"path to pdf.pdf", "application/pdf");
    }

    public ActionResult FinalPage()
    {
        return View();
    }

View

<script>

    function showfile() {
        window.open('<%= Url.Action("GetFile", "Home")%>')
    }

</script>

<%= Html.ActionLink("click", "FinalPage", "Home", null, new { onclick = "return showfile();" }) %>

This will open up a new window and get the file returned to display, but also move the other browser window onto the final page on the same click.

Hope this helps.

Edit

Updated to run off a submit button as per comment ... in answer to the comment, yes you can do it off a submit button :-)

<script>

    function showfile() {
        window.open('<%= Url.Action("GetFile", "Home")%>')
    }

</script>

<% using(Html.BeginForm("FinalPage", "Home")) { %>

    <input type="Submit" value="click" onclick="return showfile();" />

<% } %>

Hope this helps :-)

like image 130
WestDiscGolf Avatar answered Feb 22 '23 10:02

WestDiscGolf


WestDiscGolf, to download on the same page use '_self' :

function showfile() {
        window.open('PATH','_self')
    }
like image 35
Milton Quirino Avatar answered Feb 22 '23 11:02

Milton Quirino