Øyvind WH
Øyvind WH

Reputation: 33

Render view and download file in the same request

When a user has completed a form the user is redirected to the thank you page. The thank you page shall render it's view, but also download a file (pdf / a stream).

I would prefer to do this without using javascript like this return both a file and a rendered view in an MVC3 Controller action and I would prefer to get the Save As dialog.

Has MVC any conventions that can handle this?

Upvotes: 3

Views: 756

Answers (2)

Anirudha Gupta
Anirudha Gupta

Reputation: 9289

Did you tried meta refresh Trick.

<META HTTP-EQUIV='REFRESH' CONTENT='5;URL=http://www.example.com/test.txt'>

Remember to set the header Content-Disposition: attachment for the file that you want to download in browser.

Upvotes: 1

Chris Pratt
Chris Pratt

Reputation: 239270

As @BenRobinson pointed out, you can't return two responses from a single request. No, MVC doesn't have any conventions to handle this because it's a fundamental limitation of the platform you're developing on, the Internet, and specifically the TCP/IP and HTTP protocols.

Fundamentally, the web revolves around what's called the request-response cycle. A client (usually a web browser) issues a request to a server, and that server responds with the requested resource. What you're talking about would be akin to request-response-response, which is not possible. The server cannot just up and send a response to a client without first receiving a request.

As a result, your options are:

  1. Use JavaScript to programmatically issue another request, such as by setting location.href as the accepted answer on your linked question suggests.

  2. Provide a link/button/whatever to allow the user to initiate a request for the file manually.

That's it. Either way, you need a new request, either initiated by JavaScript or the end user to get the file.

Upvotes: 2

Related Questions