Export pdf file using ajax in MVC C #

0

I would like to know how to export an excel file using ajax, I have tried in the following way, but it does not work:

$("#ajax_loader").css("display", "");
        var formato = "PDF";

        //window.location.href = url;
        //$("#ajax_loader").hide();
        var fd = new FormData();
        fd.append("format", formato);
        fd.append("nombreObra", $('#nombre_obra').val());
        $.ajax({
            type: "POST",
            url: '<%= Url.Action("Export", "Obras")%>',
            data: fd,
            DataType: 'json',
            contentType: false,
            processData: false,
            success: function (data) {
                $("#ajax_loader").hide();
            }
        });
 });

If anyone has any ideas, I would really appreciate it. Greetings.

    
asked by Danilo 03.07.2018 в 01:09
source

1 answer

0

The generation of a pdf should be done on the server side, in the code that you have invoked an action of the asp.net mvc controller, but it is not necessary to send any FormData just send a simple json

The issue is not like invoking the action since with the $ .ajax you can do it without problems, but how you receive the pdf generated on the server

The article describes a possible way

Generate and Download PDF file on Ajax Post method, C #

the idea is that using ajax you invoke a controller action

    [HttpPost]
    public ActionResult Save()
    {

        // write code here to save the data in database. 
        var fName = string.Format("MYPDF-{0}.pdf", DateTime.Now.ToString("s"));
        using (var ms = new MemoryStream())
        {
            using (var document = new Document(PageSize.A4, 50, 50, 15, 15))
            {
                PdfWriter.GetInstance(document, ms);
                document.Open();
                document.Add(new Paragraph("HelloWorld"));
                document.Close();
            }

            var bytes = ms.ToArray();              
            Session[fName] = bytes;
        }

        return Json(new { success = true, fName }, JsonRequestBehavior.AllowGet);
        //return View();
    }
     public ActionResult DownloadInvoice(string fName)
     {
         var ms =  Session[fName] as byte[] ;
         if(ms == null)
             return new EmptyResult();
         Session[fName] = null;
         return File(ms, "application/octet-stream", fName);
     }

so that from the client you use

 $("#btnSave").click(function () {
     $.ajax({
         type: 'POST',
         url: "/home/save",
         dataType: "json",
         success: function (resultData)
         {
             if (resultData.success) {
                window.location = "/home/DownloadInvoice" + "?fName=" + resultData.fName;
             }
         }
    });
 })

when using the window.location, download the pdf that is temporarily in the Session

    
answered by 29.09.2018 / 03:28
source