Question

I have a Generic Handler (DownloadHandler.cs) which serves as both generating a pdf and downloading a pdf. When generating I use a jQuery ajax call and when downloading I use a form element which is submitted. The problem is that the form element cancels the generate request and therefore the "success" event never gets called (See image below).

Status List

Generate code (Gets called from a button):

$.ajax({
    type: "POST",
    url: "/DownloadHandler.ashx",
    data: {
        GeneratePdf: true
    },
    success: function (result) {
        console.log(result);
    },
    error: function (errorMessage) {
        console.log(errorMessage);
    }
});

Download code (Gets called from a button):

var data = { "GeneratePdf": false }

var inputs = '';

$.each(data, function (key, value) {
    inputs += '<input type="hidden" name="' + key + '" value="' + value + '" />';
});

$('<form action="/DownloadHandler.ashx" method="POST">' + inputs + '</form>').appendTo('body').submit().remove();

DownloadHandler:

public void ProcessRequest(HttpContext context)
{
    if (!String.IsNullOrEmpty(context.Request["GeneratePdf"]) && Convert.ToBoolean(context.Request["GeneratePdf"]))
    {
        Thread.Sleep(3000);
        context.Response.Clear();
        context.Response.Write("GENERATING");
        context.Response.Flush();
    }
    else
    {
        Thread.Sleep(3000);

        FileInfo pdfFile = new FileInfo(@"C:\1.pdf");

        context.Response.Clear();
        context.Response.AddHeader("Content-Disposition", "attachment; filename=" + pdfFile.Name);
        context.Response.AddHeader("Content-Length", pdfFile.Length.ToString());
        context.Response.ContentType = "application/octet-stream";
        context.Response.WriteFile(pdfFile.FullName);
        context.Response.Flush();
    }
}

public bool IsReusable
{
    get
    {
        return false;
    }
}

I just added a Thread.Sleep to demonstrate the generation of the pdf. Am I missing something or should I use some other method?

Was it helpful?

Solution

Maybe you can try targetting a tiny dynamic iframe on your page with your form. Something like :

var data = { "GeneratePdf": false }

var inputs = '';

$.each(data, function (key, value) {
    inputs += '<input type="hidden" name="' + key + '" value="' + value + '" />';
});

var f = $('<form action="/DownloadHandler.ashx" method="POST">' + inputs + '</form>');


var iframe = $('<iframe src="about:blank"/>')  // should be made tiny/transparent with some css
              .appendTo('body');

iframe.contents().find('html').append(f);
f.submit().remove();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top