CsvActionResult没有在View - C#MVC4中提示文件下载

时间:2016-03-08 05:50:13

标签: c# asp.net-mvc asp.net-mvc-4 csv download

我正在使用$.post从我的视图中调用自定义操作,并使用它发送一些用户生成的参数:

$("#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行动结果:

[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" }; 
}

最重要的部分是CsvActionResult类:

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("\",");
    }
}

当我查看控制台时,我可以看到正在返回数据,但它不会在浏览器中提示文件下载。所以我确实需要在返回时使用data做一些事情。我以为它会自动提示文件下载。

任何帮助都将不胜感激。

0 个答案:

没有答案