【发布时间】:2013-11-20 06:37:57
【问题描述】:
我对控制器进行了 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!");
}
});
}
我的问题是将控制器返回的逗号分隔字符串下载为 .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 中不运行。任何帮助将非常感激。谢谢。
【问题讨论】:
标签: javascript jquery ajax asp.net-mvc csv