1

I have an action with this code:

Response.Clear();
Response.ContentType = result.MimeType;
Response.Cache.SetCacheability(HttpCacheability.Private);
Response.Expires = -1;
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=File.pdf");
Response.BinaryWrite(result.DocumentBytes);
Response.End();
return null;

and I call this action from a View using JavaScript

$.ajax({
        url: '@Url.Action("GenerateFile")',
        type: "POST",
        data: printData,
        dataType: "json"});

My code in the action executes, but I didn't see any pdf file. I think this happens because I return null or do something else wrong. How can I fix this and show the file (show save file dialog) using JavaScript?

2 Answers 2

1

You won't get any Save File dialog when you fetch something using AJAX.

Also, your AJAX call specifies that the result should be JSON, so jQuery will try to parse the PDF as JSON, and that naturally ends up as an error message.

To get a Save File dialog you have to open the file as a regular page:

window.location = '@Url.Action("GenerateFile")?' + printData;
Sign up to request clarification or add additional context in comments.

5 Comments

window.location would initiate a GET request, not POST as requested.
@haim770: Well, it's also requested that it should return JSON, which of course is not possible, so I wouldn't think that the code specifies the exact way to fetch the response. If it however does require a post, you can do that with an HTML form. The point is that it has to be requested as a regualr page, not using AJAX.
You're right. it's just that the dataType option is less important than the type because the MVC Action may be restricted to [HttpPost].
How can I add JS param to '@Url.Action("GenerateFile")'?
@Std_Net: Add it to the URL as query strings, or if you need to make a post, add it as hidden fields in the HTML form.
0

I think you are right in saying that the problem lies with returning null, the response that you have set is being overwritten further down the line. Try this:

return File(result.DocumentBytes, "application/pdf");

EDIT

Sorry I didn't read the question properly. As Guffa mentioned, the problem lies in the way you are calling this action via javascript.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.