I am calling a custom action from my view with a $.post
and sending a couple user generated parameters with it:
$("#submitReport").click(function () {
var carData = $("#car-select").val();
var bikeData = $("#bike-select").val();
if (carData && bikeData !== null) {
$.post('/Reporting/ExportToExcel', $.param({ carData: carData, bikeData: bikeData }, true), function(data) {
console.log(data);
});
}
});
Csv Action Result:
[HttpPost]
public CsvActionResult ExportToExcel(string[] carData, string[] bikeData)
{
var dt = new DataTable();
// Add all the stuff into the datatable
return new CsvActionResult(dt) { FileDownloadName = "MyReport.csv" };
}
And the most important part, the CsvActionResult
class:
public sealed class CsvActionResult : FileResult
{
private readonly DataTable _dataTable;
public CsvActionResult(DataTable dataTable)
: base("text/csv")
{
_dataTable = dataTable;
}
protected override void WriteFile(HttpResponseBase response)
{
var outputStream = response.OutputStream;
using (var memoryStream = new MemoryStream())
{
WriteDataTable(memoryStream);
outputStream.Write(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
}
}
private void WriteDataTable(Stream stream)
{
var streamWriter = new StreamWriter(stream, Encoding.Default);
WriteHeaderLine(streamWriter);
streamWriter.WriteLine();
WriteDataLines(streamWriter);
streamWriter.Flush();
}
private void WriteHeaderLine(StreamWriter streamWriter)
{
foreach (DataColumn dataColumn in _dataTable.Columns)
{
WriteValue(streamWriter, dataColumn.ColumnName);
}
}
private void WriteDataLines(StreamWriter streamWriter)
{
foreach (DataRow dataRow in _dataTable.Rows)
{
foreach (DataColumn dataColumn in _dataTable.Columns)
{
WriteValue(streamWriter, dataRow[dataColumn.ColumnName].ToString());
}
streamWriter.WriteLine();
}
}
private static void WriteValue(StreamWriter writer, String value)
{
writer.Write("\"");
writer.Write(value.Replace("\"", "\"\""));
writer.Write("\",");
}
}
When I look in the console, I can see that the data is being returned, but it doesn't prompt a file download in the browser. So I actually need to do something with the data
when it is returned. I thought it would prompt a file download automatically.
Any help would be appreciated.