如何处理.ajax post中的FileStream返回类型?

时间:2013-01-06 03:08:04

标签: ajax asp.net-mvc actionlink actionresult

我通过以下代码发送JSON对象.. 控制器返回CSV格式的值,应提供promt打开或保存为CSV文件。我无法理解代码应该成功编写的内容:function(result)

导出链接

Html.ActionLink("Export", "", "", null, new { @onclick = "return exportData();"})

function exportData() {

var searchViewModel = getExLogSearchModelData();
var path = getAbsolutePath("ExclusionLog", "ExportData");
$.ajax({
    url: path,
    cache: false,
    contentType: 'application/json; charset=utf-8',
    dataType: 'html',
    type: 'POST',
    data: JSON.stringify(searchViewModel),
    success: function (result) {
    },
    error: function (error) {
        $("#voidcontainer").html("Error");
    }
});

}

Controller ActionResult

    public ActionResult ExportData(ExclusionLogSearchViewModel postSearchViewModel)
    {
        try
        {
            IEnumerable<ExclusionLogViewModel> exclusionLogData = null;
            exclusionLogcData = this._workerService.GetExclusionLogData(postSearchViewModel);

            return CSVFile(exclusionLogMembershipSyncData.GetStream<ExclusionLogViewModel>(), "ExclusionLogTables.Csv");
        }
        catch (Exception ex)
        {
                throw ex;
        }
        return null;
    }

你能建议怎么做吗?

1 个答案:

答案 0 :(得分:3)

我遇到了同样的问题而我找不到使用$.ajax下载文件的方法,但我发现了一个出色的JavaScript库,提供了类似的行为:

https://github.com/johnculviner/jquery.fileDownload

你只需要调用这样的东西:

$.fileDownload(path, {
    httpMethod: 'POST',
    data: JSON.stringify(searchViewModel),
    success: function (result) {
    },
    error: function (error) {
        $("#voidcontainer").html("Error");
    }
});

记得在控制器中创建cookie。在src/Common中,有适合您的操作过滤器。