2015-05-29 72 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

相关问题