Return PDF to browser using JSON and MVC?
I have a link as follows.
@Html.ActionLink("Create Report", "Screenreport", "Reports", null, new { @cl开发者_如何学JAVAass = "subNavA AddBorderTop", id = "screenReport", title = "Create Report" })
Once the link is clicked, I have a the following jQuery code which creates a JSON object and post the information.
$().ready(function () {
// Create Report fron the screen data
$("#screenReport").live("click", function (event) { GenerateScreenReport(this, event); });
}) /* end document.ready() */
function GenerateScreenReport(clikedtag, event) {
var table = $(".EvrakTable").html();
var screendata = tableParser(table);
var Screentable = { Screenlist: screendata };
var myurl = $(clikedtag).attr("href");
var title = $(clikedtag).attr("title");
$.ajax({
url: myurl,
type: 'POST',
data: JSON.stringify(Screentable),
dataType: 'json',
contentType: 'application/json',
success: function () { alert("Got it"); }
});
};
To Handle JSON I have the following two classes. Realize two classes in the same namespace
namespace MyProject.ViewModels
{
public class Screenrecord
{
public string Fname{ get; set; }
public string LName { get; set; }
public string Age { get; set; }
public string DOB { get; set; }
}
public class Screentable
{
public List<Screenrecord> Screenlist { get; set; }
}
}
ANd in my controller, I have the following code:
[HttpPost]
public FileStreamResult Screenreport(Screentable screendata)
{
MemoryStream outputStream = new MemoryStream();
MemoryStream workStream = new MemoryStream();
Document document = new Document();
PdfWriter.GetInstance(document, workStream);
document.Open();
document.Add(new Paragraph("Hello World"));
document.Add(new Paragraph(DateTime.Now.ToString()));
document.Close();
byte[] byteInfo = workStream.ToArray();
outputStream.Write(byteInfo, 0, byteInfo.Length);
outputStream.Position = 0;
return new FileStreamResult(outputStream, "application/pdf");
}
This code is supposed to gerate PDF. if I leave [HttpPost] as it is, it does NOT generate PDF and it goes to /Screenreport page, however I see my JSON is passed to the controller properly. (screendata is populated properly - in controller)
But if I comment out [HttpPost], it DOES generate a PDF but screendata (in controller) is null.
Can someone please explain whats's going on and help me figure it out. Thanksin advance.
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.
精彩评论