1

I have some code to export the results of a search to a CSV file:

$("#exportButton").click(function () {

    var url = "/Stuff/ExportSearchResults";
    var searchInput = readInput();

    $.post(url, searchInput, function (data) {
        // This is where I'm clueless.
        // I'm getting data back but not sure how to make the
        // browser show a prompt to download the file.
        console.log(data);
    });
});

At the server side (ASP.NET MVC 4) there's this:

[HttpPost]
public FileResult ExportSearchResults(SearchInput model)
{
    string csv = GenerateCsv(model);
    return File(new UTF8Encoding().GetBytes(csv), "text/csv", "Export.csv");
}

So the good thing is that I'm getting data back in the console. I'm just not sure how I would make the browser show a prompt to download a file.

3
  • 1
    Short answer, you should't use ajax for this kind of task, but a direct call instead... Commented Nov 9, 2016 at 23:52
  • doing this successfully cross browser could be painful - maybe FileSaver could help Commented Nov 9, 2016 at 23:53
  • 1
    window.location.href = '/Stuff/ExportSearchResults'; try like this Commented Nov 10, 2016 at 5:19

1 Answer 1

1

Here for this question we can go with comment from https://stackoverflow.com/users/5349021/sreepathy-sp

At Client side

$("#exportButton").click(function () {

       var url = "/Stuff/ExportSearchResults";
       var searchInput = readInput();

       window.location.href = '/Stuff/ExportSearchResults?searchInput='+searchInput ;
});

At server side

[HttpGet]
public FileResult ExportSearchResults(string model)
{
    string csv = GenerateCsv(model);
    Stream stream = new MemoryStream(new UTF8Encoding().GetBytes(csv));
    return File(stream , "text/csv", "Export.csv");
}

Hope this will help you out.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the help. I need to use a POST though. We can't have the parameters showing up in the url.
@Aetherix : can you please give clarity for your readInput();. If its a data retrieved from database, we can recreate the post model in our method ExportSearchResults .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.