Return PDF to browser using JSON and MVC?

后端 未结 2 502
醉话见心
醉话见心 2021-01-13 17:59

I have a link as follows.

@Html.ActionLink(\"Create Report\", \"Screenreport\", \"Reports\", null, new { @class = \"subNavA AddBorderTop\", id = \"screenRe         


        
相关标签:
2条回答
  • 2021-01-13 18:12

    I feel obligated to post my answer since I didn't hear from anyone. I ended up creating a form that includes a hidden input, then saved my json object in the hidden input and then submit the form. This time I will get input as an string not a json or xml.

    var $hidInput = $("#dataToReport"); 
    $hidInput.val(JSON.stringify(Screentable)); 
    $('#frmScreenreport').submit(); 
    

    Thanks all anyways.

    0 讨论(0)
  • 2021-01-13 18:24

    You cannot use AJAX to download files, because javascript doesn't allow you to save the downloaded content. To workaround this you need to take 2 steps.

    First: make the HTTP Post request, and in the controller action we would store the File content in a Memory stream.Second: on success make another call by setting the window.location to the Download Action method

    In your Controller create this 2 actions:

    public ActionResult GenerateFile()
        {
            MemoryStream fileStream = new MemoryStream { Position = 0 };
            //position = 0 is important
    
            var fName = string.Format("File-{0}.xlsx", DateTime.Now.ToString("s"));
            Session[fName] = fileStream;
            return Json(new { success = true, fName }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult DownloadFile(string fName)
        {
            var ms = Session[fName] as MemoryStream;
            if (ms == null)
                return new EmptyResult();
            Session[fName] = null;
            return File(ms, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fName);
        }
    

    In your javascript:

    $('#Donwload-button').click(function () {
        data = JSON.stringify(YOURDATA);
        $.ajax({
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            type: 'POST',
            url: "/YOURCONTROLLER/GenerateFile",
            data: data,
            success: function (d) {
                if (d.success) {
                    window.location = "/YOURCONTROLLER/DownloadFile" + "?fName=" + d.fName;
                }
            },
            error: function () {
               alert("Error");
            }
        });
    
    });
    
    0 讨论(0)
提交回复
热议问题