从AJAX帖子中调用FileContentResult时不会生成文件

时间:2019-01-26 09:14:41

标签: c# 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帖子有关,因为从我所见,这是它运行正常与否的唯一区别。

这是我得到的答复-就我所知...看起来还不错...?我有什么想念的吗? enter image description here

1 个答案:

答案 0 :(得分:0)

所以我只是离开了AJAX呼叫,而是现在打电话:

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

似乎做得很好。