views:

431

answers:

1

Hi, I have a ASP.NET MVC controller with a method which needs to serve up a file to the client(browser). The controller action is invoked with a JQuery $.ajax call. The user needs to be prompted to download the file once the controller action has finished.

I used Response.Transmitfile/Response.WriteFile in the controller method but both have not prompted me to download the file in IE browser even though the file has been created and I am using the right file path as well.

When i invoke the same method directly by typing the controller URL in the browser I am prompted immediately to download the file created.

Could anyone let me know if there is something missing in this flow ?

I suspect it is the way I am calling the controller action in JQuery. How do i use the response of the JQuery Ajax call to ensure the client is prompted to download the file ?

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult CreatePresentation(string id)
    {
     //do something here , create the file and place in a location on the server itself
       string filename = Path.GetFileName(filePath);
        Response.ContentType = "APPLICATION/OCTET-STREAM";
        System.String disHeader = "Attachment; Filename=\"" + filename +
           "\"";
        Response.AppendHeader("Content-Disposition", disHeader);
        FileInfo fileToDownload = new FileInfo(filePath);
        Response.WriteFile(fileToDownload.FullName);
    }

On the Javascript side, this is how i invoke the controller action

function CreatePresentation()
{ 
// something here
     $.ajax({
   type: "POST",
   url: "http://localhost:4844/ActionBar/CreatePresentation",
   data:data
 });
} // end of funtion

Thanks in advance for your help ! Sirish

+1  A: 

when you use $.ajax, or for that matter any other AJAX mechanism, you're going around the normal browser file-transfer pipeline. It's the main pipeline that trigger's the browser's Save This File dialog, not the AJAX one.

To achieve what you want, you'll want to use a synchronous location change rather than an asynchronous one: rather than using $.ajax, just set document.location.

DDaviesBrackett
This is basically right, but if you really need a POST, then you'll have to programmatically submit a form.
Matthew Flaschen
I thought to mention that, but then rereading Sirish's question he mentions that typing the address into the address bar (which generates a GET) works. So he doesn't need a POST.
DDaviesBrackett