2015-05-29 49 views
1

我正在使用SelectPdf處理將網頁轉換爲pdf文件的任務。 SelectPdf不支持動態頁面。所以我想用Ajax將網頁作爲html傳遞。Ajax無法將HTML頁面作爲參數傳遞給後面的代碼

由於某些原因,當我通過普通的字符串它的作品,但當我改變使用變量(與HTML作爲價值)它沒有。我不知道html內容是否太大,但是我嘗試了更少的內容,仍然是同樣的問題。任何幫助將不勝感激。

該項目語言爲VB.Net,頁面爲vbhtml,後面的代碼爲控制器。

請參閱我已經實現的代碼如下:

VIEW

  var btn = $('#BtnCreateHtmlToPdf'); 

      btn.click(function() { 

      var theHtml = document.documentElement.innerHTML; 

      //Just to see there is a value 
      alert(theHtml) 

      $(function() { 
       $.ajax({ 
        type: 'post', 
        url: "/CreatHtmlToPdf/CreatePdf", 
        dataType: "html", 
        data: { HTML: theHtml } 
       }) 
       .done(function (results) { 
        alert("Html data: " + results); 
       }); 
      }); 
      }); 

後面的代碼

Public Class CreatHtmlToPdfController 
    Inherits Controller 

    ' GET: CreatHtmlToPdf 
    Function Index() As ActionResult 

     Return View() 
    End Function 

    <HttpPost()> 
    Function CreatePdf(ByVal HTML As String) As ActionResult 

     Dim doc As PdfDocument 

     ' read parameters from the webpage 
     Dim htmlString As String = HTML 

     ' instantiate a html to pdf converter object 
     Dim converter As New HtmlToPdf() 

     ' create a new pdf document converting an url 
     If (HTML <> String.Empty) Then 

      doc = converter.ConvertHtmlString(htmlString) 


     End If 


     ' save pdf document 
     Dim pdf As Byte() = doc.Save() 

     ' close pdf document 
     doc.Close() 

     ' return resulted pdf document 
     Dim fileResult As FileResult = New FileContentResult(pdf, "application/pdf") 
     fileResult.FileDownloadName = "Results_page.pdf" 
     Return fileResult 

    End Function 

    'Declaration 
    'Public Property EnablePageMethods As Boolean 

End Class 
+0

你有沒有嘗試過dataType到json? – casper123

回答

0

嘗試增加你上面的CreatePdf功能ValidateInput(false)屬性,以防止標準的ASP MVC v阻止發佈HTML的alidation。

<HttpPost()> _ 
<ValidateInput(false)> _ 
Function CreatePdf(ByVal HTML As String) As ActionResult 

可選,如果你接受一個ViewModel類,你可以在AllowHTML屬性添加到包含您的HTML數據的一個屬性。

+0

非常感謝。我現在有html值,但有一個問題是值在Nothing和傳遞的html值之間切換。因此,在調用庫來轉換值時,那麼就是Nothing導致代碼中的錯誤。 有沒有辦法阻止參數切換。我懷疑對Ajax發出了多個請求,但我只點擊了一次按鈕。 – Pealife

+0

嘗試HTML是否不是Nothing並且HTML <> String.Empty。另外,將所有doc.Save(),doc.Close()等代碼放在該If塊中。 – N0Alias

+0

不幸的是,仍然表現得一樣。之前和現在它的行爲就像是在運行週期中的循環。檢查更改時間: 如果HTML IsNot運算沒有AndAlso HTML <>的String.Empty然後 DOC = converter.ConvertHtmlString(htmlString) PDF = doc.Save() doc.Close() 結束如果 – Pealife