Reputation: 103
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");
}
Upvotes: 2
Views: 15435
Reputation: 12491
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
}
Upvotes: 7