Share via


Returning a File doesn't work

Question

Friday, January 20, 2012 2:07 PM

When the user clicks on an Export button, a jQuery event fires which in turn POSTs to a controller action that returns a File(). However, nothing happens after the controller method is executed - there's no file download prompt.

Stripped down to the very bare minimum:

Client side:

$.post(
    'MyController/ExportToExcel',
    { }
)

Server side:

[HttpPost]
[ValidateInput(false)]
public ActionResult ExportToExcel()
{
    string output = "<html></html>";

    return File(Encoding.UTF8.GetBytes(output), "application/vnd.ms-excel", "Export.xls");
}

Is there something else I need to do to make this work?

All replies (6)

Friday, January 20, 2012 7:19 PM ✅Answered

unless you are using the new html5 file api (IE 10, webkit), you can not download a file via ajax. well you can download it, just add a success routine and the first parameter is the file as a string, but can not do much with it.


Friday, January 20, 2012 7:33 PM ✅Answered

window.open('@Url.Content("~/MyController/ExportToExcel")')


Saturday, January 21, 2012 4:20 PM ✅Answered

do a form post to a target.

  <form id="excellExport" target="_blank" method="post" action="@Url.Action("exporttoexcell")"></form>

function export(data){
    var $form = $('excellExport').html('');
    for (i in data)  $form.append($('<input type="hidden" />')
             .attr('name',i)
             .val(data[i]);
    $form.submit();
} 

Friday, January 20, 2012 3:48 PM

http://stackoverflow.com/questions/5826649/returning-a-file-to-view-download-in-mvc


Saturday, January 21, 2012 1:20 AM

window.open('@Url.Content("~/MyController/ExportToExcel")')

Is there any way to pass parameters? I'd rather not make a second database call to get the data to export when it's already sitting on the page in JSON format.


Saturday, January 21, 2012 5:01 AM

window.open('@Url.Content("~/MyController/ExportToExcel")'  +  '/1')