首页 > 解决方案 > 从 AJAX 帖子调用时,FileContentResult 不生成文件

问题描述

如果这有点含糊,我深表歉意,但是问题本身并没有泄露太多。我一直在编写一个使用 MigraDoc 生成 PDF 的应用程序。用于生成和下载PDF的控制器方法如下:

    public FileContentResult ConvertToPDF(int reportTypeId, string cultureName, int headerFooterTemplateId, int baseClassId, string baseTypeName)
    {
        try
        {
            string resourcePath = @"C:\TFS\Products\EnGenero\Trunk\EnGenero Application\RiskNetResources\bin\Debug\RiskNetResources.dll"; // --<<-- Reference this

            byte[] result = new DocumentWriter().ConvertDocumentToPDFSharp(GetSeedData(reportTypeId, cultureName, resourcePath, headerFooterTemplateId, baseClassId));

            return new FileContentResult(result, "application/pdf")
            {
                FileDownloadName = "MyReportFile.pdf"
            };
        }
        catch (Exception ex)
        {
            Logger.Instance.LogError("Error in ConvertToPDF", ex);
            return new FileContentResult(GetBytes("Error fetching pdf, " + ex.Message + Environment.NewLine + ex.StackTrace), "text/plain");
        }
    }

在开发过程中,这工作正常,当上面的代码被点击时,通过浏览器下载 PDF 很好。在开发过程中,我直接从带有硬编码参数的 JQuery 对话框调用此控制器方法。

但是,我进一步开发了应用程序,现在通过局部视图中的 Ajax Post 调用此操作方法。

function CreateDocumentPDF() {

    var baseClassId = @Html.Raw(Json.Encode(ViewData["baseClassId"]));
    var baseTypeName = @Html.Raw(Json.Encode(ViewData["baseTypeName"]));
    var reportTypeId = $j('#ddlReportType option:selected').attr('Value');
    var branchId = $j('#ddlBranch option:selected').attr('Value');
    var languageId = $j('#ddlLanguage option:selected').attr('Value');

    $j.ajax({
        url: appRoot + 'DocumentPDFPrinter/ConvertToPDF',
        type: 'post',
        data: { 'reportTypeId': reportTypeId, 'cultureName': languageId, 'headerFooterTemplateId': branchId, 'baseClassId': baseClassId, 'baseTypeName': baseTypeName },
        success: function (data) {
            closeDefaultPopup();
        },
        failure: function () {
            alert("Error Generating PDF.");
        }
    });
}

传递了完全相同的参数值,并且控制器操作按预期运行,但是现在没有生成/下载文件。

我只能想象这与 Ajax 帖子有关,因为这是我所看到的运行正常与否之间的唯一区别。

这是我得到的回应-据​​我所知,看起来还不错...?我错过了什么吗? 在此处输入图像描述

标签: c#ajaxfilecontentresult

解决方案


所以我只是简单地远离了 AJAX 调用,而是现在调用:

    window.location = appRoot + "DocumentPDFPrinter/ConvertToPDF?reportTypeId=" + reportTypeId + "&cultureName=" + languageId etc...

这似乎很好地完成了这项工作。


推荐阅读