I'm using MVC 3. I've created a csv file in an Action Method on the server (called GetCSV()). It's an [HttpPost] action method. What I'd like to do is send that csv file directly to the web browser as a downloadable file. I got this to work using window.open(), however, that is a GET method by nature and I need something that makes use of POST since I will need to pass a lot of parameters into it. Ideally, I would like to use Ajax since I can easily pass a whole lot of parameters back to the server using this approach. Any ideas in how I can use an Ajax call to pass the parameters to the server and then somehow have the response open as a downloadable file? I'd appreciate any advice!
-
Can't you return a path? – aIKid Apr 06 '13 at 23:24
-
Well, I'm not actually saving the csv on the server disk. It's all being generated in the server memory. Eventually, I'd like to do that since saving to disk will make it much more scalable, but for now it's being done in memory. – TheDude Apr 06 '13 at 23:31
2 Answers
My solution for this was to use Microsoft's MVC 3 Ajax Form instead of JQuery's Ajax. I found out by pure accident a number of months ago that if you don't specify a "success" function for an MVC Ajax form, it just sends the file to the web client for download. This is what I need to happen. I tried this and it did indeed work as intended.

- 1,421
- 4
- 29
- 54
You can't save a file to the local filesystem using javascript (at least in a standard way supported by all browsers), or ajax. That's why the recommended approach is to do it without ajax, and usually through a GET.
You can however convert a json object with parameters to a URL, through jquery's .param() as shown on this answer.
If indeed you want to explore the javascript alternative, maybe you can look into the FileSystem API supported only by chrome AFAIK.

- 1
- 1

- 11,298
- 2
- 30
- 58
-
Many months ago, I found out by pure accident that unobtrusive Ajax (built into mvc 3) sends the json file directly to the page for download if you don't specify a "success" function to catch the ajax response. I will give this a try on Monday and let you guys know if it works. Unless, of course, somebody tries it out before that. ;) – TheDude Apr 07 '13 at 03:19