javascript - 在.NET MVC JQuery Ajax中调用下载数据为.csv

标签 javascript jquery ajax asp.net-mvc csv

我对 Controller 进行了 ajax 调用,以获取以下格式的逗号分隔数据,

public ActionResult GetSearchDataforDownloadtoCSV(string pSearchbykeyword, string pRequestCode)
{
   ReportsBE _lReportsBE = new ReportsBE();
   _lReportsBE.SearchKeyword = pSearchbykeyword;
   _lReportsBE.RequestCode = pRequestCode;

     List<ReportsBE> lstResult = new List<ReportsBE>();
     lstResult = _objReports.GetPackagelistAll_Search(_lReportsBE);

    StringBuilder sb = new StringBuilder();
    sb.Append("Request");
    sb.Append(",");
    sb.Append("Description");
    sb.Append("\n");

    foreach (var _RepBE in lstResult)
    {

        if (_RepBE.RequestCode != null)
        sb.Append(Escape(_RepBE.RequestCode));
        sb.Append(",");
        if (_RepBE.Description != null)
        sb.Append(Escape(_RepBE.Description));

        sb.Append("\n");
    }

return Json(sb.ToString());
}

这是我的 HTML,

@Html.LabelFor(model => model.SearchKeyword, "Search Packages by Keyword")
@Html.TextBoxFor(model => model.SearchKeyword, new { style = "width: 500px;" })

<button type="button" id="btnExport" onclick="DownloadCSV()" value="Export to CSV">Export to CSV</button>

这是我的 ajax 调用,

function DownloadCSV() {
        var _pSearchbykeyword = $('#SearchKeyword').val();
        var _pRequestCode = $('#RequestCode').val(); 

        var postData = {
            pSearchbykeyword: _pSearchbykeyword == '' ? '' : _pSearchbykeyword
            , pRequestCode: _pRequestCode == '' ? '' : _pRequestCode
        };

        $.ajax({
            type: 'POST',
            url: '@Url.Action("GetSearchDataforDownloadtoCSV", "Reports")',
            data: postData,
            success: function (data) {
                if (data != null) {
                    // need to code here to through comma seperated data as csv file...
                }
            },
            error: function (xhr, ErrorText, thrownError) {
                alert("No Records Found!");

            }
        });

    }

我的问题是将 Controller 返回的逗号分隔字符串下载为 .csv 文件。 请帮忙。

我尝试像下面这样浏览文件,

var uri = 'data:text/csv;charset=utf-8,' + escape(data);
var downloadLink = document.createElement("a");
downloadLink.href = uri;
downloadLink.download = "SearchList.csv";
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);

由于查询字符串限制,此代码可以在 Chrome 中运行,但不能在 IE 中运行。任何帮助将非常感激。谢谢。

最佳答案

不要使用 AJAX,而使用标准 HTML <form> :

@using (Html.BeginForm("GetSearchDataforDownloadtoCSV", "Reports"))
{
    @Html.LabelFor(model => model.RequestCode, "Request Code")
    @Html.TextBoxFor(model => model.RequestCode, new { style = "width: 500px;" })


    @Html.LabelFor(model => model.SearchKeyword, "Search Packages by Keyword")
    @Html.TextBoxFor(model => model.SearchKeyword, new { style = "width: 500px;" })

    <button type="submit" value="Export to CSV">Export to CSV</button>
}

您无法使用 AJAX 请求下载文件的原因是您无法在 JavaScript 中显示“另存为”对话框。因此,您无法在 AJAX 成功回调中执行任何操作来提示用户保存文件。这就是为什么最简单的解决方案是使用标准表单或直接指向将提供 CSV 文件的 Controller 操作的 anchor 。

关于javascript - 在.NET MVC JQuery Ajax中调用下载数据为.csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20089110/

相关文章:

php - 插入前检查数据库中是否存在Random

jquery - 使数据角色 ="content"内的 div 响应

javascript - 添加新路径后图像不显示

javascript - 为处理程序或匿名函数指定命名函数的区别?

javascript - MongoDB 查询超过 30 秒的文档

javascript - HTML : Can anchor be clicked when it was disabled?

JavaScript - 构建 JSON 对象

javascript - React-Native for-loop through large size array 性能问题

jquery - 使用 :even or filter (":even") in jQuery

javascript - 当 View 从操作结果返回时,Select2 脚本无法正确渲染