2015-11-06 47 views
0

我尝试通过ajax调用使用ASP MVC模型 下载一个PDF文件按钮点击我的按钮时,什么都没有发生,但当我在url上添加控制器方法我的文件被下载。 我想下载它只能在点击链接仅通过ajax调用下载PDF文件ASP MVC

JS:

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

控制器:

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"); 
} 
+0

创建一个链接(和样式它看起来像一个按钮,如果这是你想要的)。 –

+0

你是什么意思“仅在按钮上单击JS”?如果您实际上是在该操作方法中创建该pdf文件,那么如何摆脱服务器端的操作? –

+0

我不能使用链接,因为我有其他的条件和JS的说明在AJAX调用之前 –

回答

4

不要使用AJAX来下载文件。这是非常棘手的,你可以在this question看到它。

无论如何,最好使用GETwindow.location.href couse文件下载异步。

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

[HttpGet] 
public FileResult DownloadFile() 
{ 
//your generate file code 
} 
+0

下面你的例子我的工程在IE中,但不是Firefox。有什么建议么? –

+0

@FreekNortier如果你还有问题,最好再问一个问题 –