Return PDF to browser using JSON and MVC? Return PDF to browser using JSON and MVC? json json

Return PDF to browser using JSON and MVC?


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");        }    });});


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.