2012-04-07 51 views
1

编程新手。我试图打印从MVC PDF文件,它工作得很好,如果我使用操作链接,这里是我的代码:MVC json vs. ActionLink

<%= Html.ActionLink("Print","GeneratePdf","Home", new { fc="Test" },null) %> 

    public ActionResult GeneratePdf(string fc) 
     { 
      Document document = new Document(); 
      MemoryStream workStream = new MemoryStream(); 
      PdfWriter.GetInstance(document, workStream); 
      document.Open(); 
      document.Add(new iTextSharp.text.Paragraph("\n\n")); 
      // need to add the user name 
      iTextSharp.text.Paragraph p = new iTextSharp.text.Paragraph("Name: " + fc); 
      p.Alignment = 1; 
      document.Add(p); 

      document.Close(); 
      byte[] byteInfo = workStream.ToArray(); 
      SendPdfToBrowser(byteInfo); 
      return null; 
     } 

    public void SendPdfToBrowser(byte[] buf) 
     { 
      string filename = "Certificate.pdf"; 

      // Prepare the headers. 
      Response.ClearContent(); 
      Response.ClearHeaders(); 
      Response.ContentType = "application/pdf"; 
      Response.AddHeader("Content-Disposition", "attachment; filename=" + filename); 

      // Write the PDF data. 
      Response.BinaryWrite(buf); 

      // Flush the buffer to the browser. 
      Response.End(); 
      Response.Flush(); 
      Response.Clear(); 
     } 

我需要使用JSON,这里是代码:

function PrintChart(fc) { 

       var fc = "Test"; 
       var url = '<%= Url.Content("~/Home/GeneratePdf") %>'; 
       $.post(url, { fc: fc }, 
      function (content) { 
       if (content != null) { 5 } 
      }, "json"); 

<input type="button" onclick="PrintChart();" value="Print" /> 

我不要收到任何错误,但不会生成PDF文件。提前致谢。

+0

其中一期工程JSON或ActionLink的,当你说这不产生你的意思是你没有得到要下载的文件 – 2012-04-07 04:02:56

+0

ActionLink的工作PDF文件。使用Json不会下载文件。 – hncl 2012-04-07 04:09:01

回答

0

你不能使用Ajax来下载文件。 jQuery $ .post()将期望来自服务器的响应是文本。 要下载文件中的Ajax方式,一般的方法是使用一个隐藏的iframe和设置的iframe的src到文件

<iframe id="hiddenFrame" src="" style="display:none; visibility:hidden;"></iframe> 

在PrintChart的URL()创建URL包括数据作为查询字符串并设置IFRAME的src:

function PrintChart(fc) { 

    var fc = "Test"; 
    var url = '<%= Url.Content("~/Home/GeneratePdf") %>'; 
    url += "?fc="+fc; 

    $('#hiddenFrame').attr('src', url); 
} 
+0

谢谢Kibria,但是如果我将它改为var fc = $('#vtest1')。val(); 它不起作用? – hncl 2012-04-07 18:22:44

+0

实际上它的工作原理是var fc = $(“#vtest1”)。我用双引号。再次感谢 – hncl 2012-04-07 19:00:15