2012-04-07 52 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