Search code examples
jqueryashx

How to: jQuery post to ashx file to force download of result?


I have an ashx handler which takes the 'html' property from the request, then returns that back to whatever called it. I also have the Content-Disposition set as attachment.

Calling the page directly works as expected, forcing a download with a save as dialog.

What I'm stuck on is this: I need to do this from javascript (jQuery). I'll be posting the content of a div and do some further processing.

Could someone give me some pointers on how this is done?

Many thanks.


Solution

  • I would (in fact, do :-) ) have a form with a hidden field, copy the content of the div to the field, and then submit the form to a hidden (display: none) iframe.

    Including a hidden iframe on the page:

    <iframe name="formTarget" src="blank.html" style="display: none">
    

    (E.g., it's initially blank. I actually literally use a blank.html file which is exactly what it sounds like, instead of (say) about:blank because the latter doesn't works quite correctly in some cases; I don't recall the details.)

    Telling the form to submit to the iframe and trigger your ashx file:

    <form ... action="your.ashx" target="formTarget" ... >
    

    Copying the content of the div to the field:

    $("#fieldId").val($("#divId").html()); // Either .html() or .text(), depending on what you want
    

    Submitting the form:

    $("#formId").submit();
    

    (Fill in the various "..."s appropriately.)

    In my case, I show an overlay div telling the user what I'm doing and start a timer that watches for the content of the iframe (for error messages) and for a status cookie (see this answer for more about the cookie trick). The overlay gets updated or removed depending on the result.