Im generating a large csv file on the server and returning it in mvc4, this takes about 30 seconds. I want to show a loading message to the user but since I cant download files using ajax I dont know what I should do. also if the file cant be generated, i.e there was no relevant data to be used to generate the file I want to be able to return a message to appear in the same page , I dont want to refresh the page or return an error code. is this possible?
-
1Make sure that your Action that returns your file to download is returning an ActionResult. Don't try to narrow it to FileContentResult, this way you can still choose to pass back a page with the error details or maybe JSON, should the process fail.Nick Albrecht– Nick Albrecht2013-04-25 19:45:09 +00:00Commented Apr 25, 2013 at 19:45
-
how can I grab the jsonresult without making an ajax request?Farhad-Taran– Farhad-Taran2013-04-25 19:58:26 +00:00Commented Apr 25, 2013 at 19:58
-
Ahh, you're right. I shouldn't have included JSON as an option in this case. It's still a valid concern however, by leaving the return type as ActionResult, you're free to return a FileResult, or a ViewResult.Nick Albrecht– Nick Albrecht2013-04-25 20:49:59 +00:00Commented Apr 25, 2013 at 20:49
2 Answers
Instead of using the FileContentResult directly to the end browser, I would return a standard View telling the user that the file is being generated. Then fire an AJAX POST to the server which triggers the file generation, and saves the result to the server. Once the server has generated the file, notify the user that it is available to download, or have the browser navigate to the file download.
Comments
You can't generate a loading message while the action is trying to return a response because the browser doesn't have an active view at that point. The best way to handle this is to create a job with AJAX (i.e. call a URL that will start the creation of the CSV file in a separate thread or process and return some sort of identitifier.) Then, you can either poll every so often to get the current status or use something like SignalR and HTML5 Web Sockets to notify the user of the status. When the creation of the file is complete, provide the user a link to the finished file.