0

So I have a string that I want to pass through Ajax into a C# controller to download it as a text file. But when the controller action runs, it never initiates a file download.

$('#download').click(function () {

    var jsonString = JSON.stringify(allLists);

    $.ajax({
        url: '/Home/Download',
        data: {data: jsonString},
        type: 'POST'
    }).done(function (result) {
        debugger;
    }).fail(function (a, b, c) {
        console.log(a, b, c);
    });
});

Here is the C#:

   public FileResult Download(string data)
    {
        return File(new UTF8Encoding().GetBytes(data.ToString()), "text/plain", "JsonOutput.txt");
    }

there are no errors, it hits the success function but never initiates a download. I'm using Chrome. Any idea what I could do differently?

SeanMC
  • 1,960
  • 1
  • 22
  • 33
  • 1
    AJAX doesn't prompt for files. But you probably don't *really* need to use AJAX for this. If you navigate the user to that file, the browser should prompt for the file save without unloading the page. – David Apr 08 '17 at 22:57
  • Are you using MVC ? – Tushar Gupta Apr 08 '17 at 22:59
  • @David there must be a better way than passing the entire text file as a URL parameter. I'm hitting the C# controller and returning the file. Identical to how I'm doing it in another project. Is there a reason why it won't just initiate a download here? Or can you be more descriptive? The other question you pointed me to is not really identical to this one. – SeanMC Apr 09 '17 at 00:25
  • @SeanKPS: Well, you're asking how to download a file via jQuery's AJAX function, so that seems pretty duplicate. Though it's *really* strange that you're sending data to the server just to have that same data sent right back. Seems instead you might want to try to just *save* the file data you already have rather than involving the server at all. This might help as well: http://stackoverflow.com/questions/2897619/using-html5-javascript-to-generate-and-save-a-file – David Apr 09 '17 at 00:29
  • @David Ok I'll look into that one. I'd just love to do it ANY other way than directing to a URL containing my text file – SeanMC Apr 09 '17 at 00:40

0 Answers0