ASP.Net MVC ItextSharp:通过jquery调用动作时不下载PDF文件

问题描述 投票:0回答:2

当我点击一个按钮然后引导弹出窗口出现一个按钮存在下载数据为pdf。当按钮单击引导弹出窗口时,然后在代码触发下面并调用服务器端操作。

$(".bol_save_as_pdf").click(function () {
    $.ajax({
    type: "GET",
    url: '@Url.Action("GeneratePDF", "TestModal")',
    success: function (data) {
        alert(data.Msg);
        },
        error: function (xhr, status, error) {
        //$("#dataDiv").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
        }
    });
    return false;
});

服务器端操作正确执行但没有出现pdf下载对话框但是当我调用相同的操作放入浏览器URL时,然后在客户端下载pdf。

看我的服务器端动作代码

[Route("DownloadPDF")]
[HttpGet]
public void DownloadPDF()
{
    //bool IsPdfGenerated = false;

    List<Student> studentsVM = new List<Student>
    {
        new Student {ID=1,FirstName="Joy",      LastName="Roy",     FavouriteGames="Hocky"},
        new Student {ID=2,FirstName="Raja",     LastName="Basu",    FavouriteGames="Cricket"},
        new Student {ID=3,FirstName="Ajay",   LastName="Das",FavouriteGames="Foot Ball"},
        new Student {ID=4,FirstName="Debu", LastName="Saha",    FavouriteGames="Tennis"},
        new Student {ID=5,FirstName="Sanjeeb",  LastName="Das",     FavouriteGames="Hocky"},
    };

    var viewToString = StringUtilities.RenderViewToString(ControllerContext, "~/Views/Shared/_Report.cshtml", studentsVM, true);
    string filepath = HttpContext.Server.MapPath("~/PDFArchives/") + "mypdf.pdf";

    MemoryStream workStream = new MemoryStream();
    StringReader sr = new StringReader(viewToString);
    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 30f, 0f);
    PdfWriter writer = PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);
    //writer.CloseStream = false;
    pdfDoc.Open();
    XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
    pdfDoc.Close();

    System.Web.HttpContext.Current.Response.ContentType = "pdf/application";
    System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;" +
            "filename=sample.pdf");
    System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    System.Web.HttpContext.Current.Response.Write(pdfDoc);
    System.Web.HttpContext.Current.Response.End();
}

我的方法有什么问题?

pdf下载框没有来,因为我正在使用bootstrap弹出窗口?寻找指引。 thaks

jquery asp.net-mvc itext
2个回答
0
投票

删除ajax并用 - @ Url.Action(“DownloadPDF”,“Home”)替换您的按钮


1
投票

此问题现已解决。我改变js代码它开始工作的那一刻。只是我需要使用window.location = '@Url.Action("DownloadPDF", "TestModal")';

$("#btndownload").click(function () {
    window.location = '@Url.Action("DownloadPDF", "TestModal")';
    return false;
});
© www.soinside.com 2019 - 2024. All rights reserved.