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

帅比萌擦擦* 提交于 2019-11-28 08:28:29

问题


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?


回答1:


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 :-)




回答2:


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

function showfile() {
        window.open('PATH','_self')
    }


来源:https://stackoverflow.com/questions/3663480/in-asp-mvc-how-can-i-return-a-new-view-and-a-file-to-the-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!