1

i try to download a pdf file on button click via ajax call using ASP MVC model when i click on my button, nothing happen but when i add the controller methode on the url my file is downloaded. i want to download it only on button click only

JS:

$('#PrintTimeSheet').click(function () {
            $.ajax({
                type: 'POST',
                url: "/Home/DownloadFile",
                success: function (response) {
                }
            });
});

Controller:

public FileResult DownloadFile()
{
    Document PDF = new Document();
    MemoryStream memoryStream = new MemoryStream();
    PdfWriter writer = PdfWriter.GetInstance(PDF, memoryStream);
    PDF.Open();
    PDF.Add(new Paragraph("Something"));
    PDF.Close();
    byte[] bytes = memoryStream.ToArray();
    Response.ContentType = "application/pdf";
    Response.AddHeader("Content-Disposition", "attachment;filename=Receipt-test.pdf");
    Response.BinaryWrite(memoryStream.ToArray());
    return File(bytes, "application/pdf");
}
Mokhtar_Nebli
  • 93
  • 1
  • 3
  • 12
  • Create a link (and style it to look like a button if that's what you want). –  Nov 06 '15 at 08:33
  • What do you mean by "only on button click only JS"? How can you get rid of action at server side if you're in fact creating that pdf file in that action method? – Andrey Korneyev Nov 06 '15 at 08:34
  • i can't use links because i have other conditions ans instructions on JS before the ajax call – Mokhtar_Nebli Nov 06 '15 at 08:36

1 Answers1

6

Don't use Ajax to download a file. It's really tricky you can see it in this question.

It's better to use GET and window.location.href cause file is downloading async anyway.

$('#PrintTimeSheet').click(function () {
   window.location.href = "/Home/DownloadFile";
});

[HttpGet]
public FileResult DownloadFile()
{
   //your generate file code
}
teo van kot
  • 12,350
  • 10
  • 38
  • 70