4

Internet explorer used to prompt a user to download an excel file after doing a Response.Write

Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition", "attachment;filename=\"sheet.xls\"");
            Response.RedirectLocation = "export.xls";
            Response.Charset = "";
EnableViewState = false;

            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

            dataGridResult.RenderControl(oHtmlTextWriter);
            Response.Write(oStringWriter.ToString());

This works when I POST back to a page with a button click event.

I am using a page as a service and doing a $.get(), but the results are sent back as HTML. I am not prompted to open the excel file. How can send the prompt out to the user?

$.get('ExcelService.aspx',
                        { batches: input },
                        function (data) {
                            alert(data);//I see HTML
                        });
P.Brian.Mackey
  • 43,228
  • 68
  • 238
  • 348

2 Answers2

2

This is a similar thread, with a similar problem ("I would like to make an async GET request that returns back a document with MIME content type and cause it to bring the browser's 'Save' dialog.")

How to specify content-type and content-disposition with $.ajax() GET response

Someone there offers a workaround to it:

If you'd like to programatically pop a save dialog box, you can use jQuery to append a hidden iframe to the page with the URL as it's src. This should pop the dialog box as necessary.


SAMPLE
jquery - on click (dont need ajax/get)
            var dynamicUrl = 'ExcelService.aspx?batches=' + input;
            $('#excelPopup').attr('src', dynamicUrl);
            window.frames["#excelPopup"].location.reload();

HTML

<iframe id="excelPopup" style="visibility:hidden;height:0px;width:0px;"></iframe>
Community
  • 1
  • 1
jglouie
  • 12,523
  • 6
  • 48
  • 65
  • +1 - I added an implementation to your answer. This works in Firefox, but does not work in IE7. IE7 is our main browser. Anybody know how to get this to work in IE7? – P.Brian.Mackey May 25 '11 at 16:37
  • I changed `window.frames["#excelPopup"]` (added missing #). I guess FF is more forgiving then IE in this case. – P.Brian.Mackey May 25 '11 at 16:44
0

You could try an Ajax post

$.ajax({        dataType: "HTML",
                cache: false,
                type: "GET",
                url: 'ExcelService.aspx';

this will prompt the get and has a bit more flexibility than just using jquery

Dontlose
  • 49
  • 1
  • 6
  • I tried this and it doesn't fix the problem. I could be missing something, but as is (with data element added), it didnt work. It hits a breakpoint, but I still do not get prompted to download the excel.xls – P.Brian.Mackey May 25 '11 at 15:03