I have a MVC application that has a Jquery Post
$.post(virtualPath + cookie + this.pageName + '/FunctionA/', parameters,function (filedata) {
alert(filedata);
},'application/csv');
}
this post is called from Javascript Event that is triggered by a buttonclick to download the file
I get the Server Side Http File Response
in the alert but cannot get it downloadable in the browser
The controller returns the Response as FileContentResult
[AcceptVerbs(HttpVerbs.Post)]
public FileContentResult FunctionA(string A, DateTime B)
{
try
{
string csv = "Make it downloadable ";
var filresult = File(new System.Text.UTF8Encoding().GetBytes(csv), "application/csv", "downloaddocuments.csv");
// return filresult;
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment; filename=Statement_" + "Downloadfile" + ".csv");
Response.Write(csv);
Response.Flush();
return filresult;
}
}
You cannot use AJAX to download files. The reason for that is because once the download succeeds and the success callback is invoked you cannot neither save the file automatically to the client browser nor you can prompt for the Save As dialog.
So instead of using javascript and AJAX to download this file simply use a standard link to the controller action which will allow the user to directly download the file.
UPDATE:
As requested in the comments section here’s an example using an anchor:
or if you need to pass lots of parameters you might prefer to use a form with hidden fields that will POST: