PDF 扔到浏览器控制台,不下载

PDF thrown to browser console, not downloading

我正在使用 Rotativa 到 ,效果很好,但现在在浏览器上我在控制台收到原始文件,没有下载对话框,没有警告,什么都没有。这是我的代码:

控制器

public ActionResult DescargarPDF (int itemId) {
        var presupuesto = ReglasNegocio.Fachada.Consultas.ObtenerPresupuesto(itemId);     
        return new Rotativa.PartialViewAsPdf("_PresupuestoFinal", presupuesto) {
            FileName = "Presupuesto_" + itemId + ".pdf",
            PageSize = Rotativa.Options.Size.A4
        };
    }

JQuery 脚本:

$(".convertirPDF").on("click", function (id) {
    var itemId = $(this).data('itemid');
    Pdf(itemId);
});

function Pdf(itemid) {
    var id = itemid;

    $.ajax({
        method: "POST",
        url: 'DescargarPDF',
        data: { itemId: id },
        cache: false,
        async: true,
    });
};

HTML

上的按钮
<button class="convertirPDF btn btn-secondary btn-info" data-itemid="@item.Id">PDF</button>

我在控制器上尝试了几个代码(结果相同),因为脚本和视图似乎工作正常。但是,我怀疑,也许 html 或脚本需要一些调整来通知浏览器它必须下载文件?

先谢谢大家了。

我找到了解决办法。它不优雅,但它有效。 所以我不需要使用 ajax 来发出请求,也不需要为按钮提供功能。我确定这个问题与 JS and/or jQuery 有关。不过,有一种更简单的方法可以做到这一点。

我将 html 按钮更改为:

<a href="DescargarPDF/?itemId=@item.Id" target="_blank" class="btn btn-secondary btn-info">PDF</a>

所以它看起来像一个按钮,但它实际上是我控制器方法的 link。我还删除了该按钮的脚本,现在它下载了文件。不是预期的名称,但仍然是。

感谢大家。编码愉快。

更新

我一直在从事同一个项目,我想我发现了为什么我的 PDF 文件被扔进了控制台。

问题是,jQuery 发出请求,因此 jQuery 管理响应。就这么简单吗。如果您在 official docs 中检查 .post(),您将看到以下内容:

The success callback function is passed the returned data, which will be an XML root element or a text string depending on the MIME type of the response. It is also passed the text status of the response.

As of jQuery 1.5, the success callback function is also passed a "jqXHR" object (in jQuery 1.4, it was passed the XMLHttpRequest object).

Most implementations will specify a success handler.

而我不是,所以默认情况下,它只是将它放到控制台。我希望这能对问题有所启发并有所帮助。编码愉快。