我正在执行一项使用 SelectPdf 将网页转换为 pdf 文件的任务。 SelectPdf 不支持动态页面。所以我想使用Ajax将网页作为html传递。
出于某种原因,当我传递普通字符串时,它可以工作,但是当我更改为使用变量(以 html 作为值)时,它不能工作。我不知道html内容是否太大,但是我尝试了更少的内容,但仍然是同样的问题。任何帮助将不胜感激。
该项目的语言是VB.Net,页面是vbhtml,后面的代码是 Controller 。
请参阅下面我实现的代码:
查看
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
最佳答案
尝试添加 ValidateInput(false)您的 CreatePdf 函数上方的属性可防止标准 ASP MVC 验证阻止发布 HTML。
<HttpPost()> _
<ValidateInput(false)> _
Function CreatePdf(ByVal HTML As String) As ActionResult
如果您接受 ViewModel 类,您可以添加 AllowHTML属性到保存 HTML 数据的单个属性。
关于javascript - Ajax 无法将 html 页面作为参数传递给后面的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30529265/