0

I have a bit of ajax that is working perfectly fine. It posts to a C# controller that returns a file. Unfortunately I think Ajax is unable to initialize the file download. I really need to post JSON. The JSON contains filters that are applied to a table by the user. I have tried posting the JSON as a string from a input but it doesn't work the same and never populates my object. I realize that my C# code below does nothing yet but return a file but I will be adding more to it after I can get the simple file download to work.

Javascript:

$.ajax(
    data: JSON.stringify(model),
    contentType: 'application/json',
    type: 'POST',
    url: 'Respondents/DownloadCSV',
    success: function () { alert('success'); },
    error: function () { alert('unsuccessful'); }
});

C#

[HttpPost]
public ActionResult DownloadCSV(RespondentViewModel model)
{
    string csv = "Name, Source, Email, City, State, Gender, Ethnicity, Age, Last Edit, Owner, Group, Status Date, Status";
    return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "DispositionReport.csv");
}
Zabavsky
  • 13,340
  • 8
  • 54
  • 79
allencoded
  • 7,015
  • 17
  • 72
  • 126
  • 3
    Possible duplicate of [jQuery post request (not AJAX)](https://stackoverflow.com/questions/4583703/jquery-post-request-not-ajax) – Cindy Meister Sep 23 '19 at 05:43

2 Answers2

1

I think the problem is the url, change it like below:

url: '/Respondents/DownloadCSV',
Lin
  • 15,078
  • 4
  • 47
  • 49
0

The solution is:

Return json object with url property

{ redirect_url: '/blabla/path/to/file/download' }

Make redirect to this url via JavaScript, on ajax success

$.ajax(
    data: JSON.stringify(model),
    contentType: 'application/json',
    type: 'POST',
    url: 'Respondents/GetJsonResult', // !!!
    success: function (result) {
            if (result.redirect_url) {
                window.location = result.redirect_url;
            }
        },
    error: function () { alert('unsuccessful'); }
});
Roman Pushkin
  • 5,639
  • 3
  • 40
  • 58