Search code examples
c#jqueryhtmlasp.net-mvcrotativa

PDF thrown to browser console, not downloading


I'm using Rotativa to generate a PDF file from a view, which works well, but now on the browser I get the raw file thrown at the console, no download dialog box, no warning, nothing. Here's my code:

Controller

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 script:

$(".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,
    });
};

Button on the HTML

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

I've tried several codes on the controller (with same result) since the script and view seems to work fine. However, I'm suspecting, maybe the html or the script need some tuning to inform the browser it has to download the file?

Thanks everyone in advance.


Solution

  • I found a solution. It's not elegant, but it works. So I didn't need to use ajax necessarily to make the request, neither to give function to the button. I'm kind of sure that the issue has something to do with JS and/or jQuery. Nevertheless, there's a simpler way to do this.

    I changed my html button to:

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

    so it looks like a button but it's really a link to my controller¡s method. I also removed the script for that button and now it downloads the file. Not with the name intended, but still.

    Thanks to everyone. Happy coding.

    UPDATE

    I've been working on the same project, and I think I found out why my PDF file was being thrown into console.

    The thing is, jQuery makes the request, so jQuery manages the response. Is that simple. If you check official docs for .post(), you'll see the following:

    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.

    And I wasn't, so, by default, it just drop it to console. I hope this throws some light into the issue and helps. Happy coding.