Web API控制器下载csv,但不能与jQuery一起工作
Web API controller downloads csv but doesn't work with jQuery
我有一个简单的web api控制器,我可以通过url导航,它将下载。csv文件。现在我试图写一些jQuery,如果你点击按钮,它会下载它,但我错过了一些东西。
public HttpStatusCode Get(string id)
{
var reportString = AskWebBusiness.Reports.GenerationQuestionReport(id);
var response = HttpContext.Current.Response;
response.ContentType = "text/csv";
response.AppendHeader("Content-Disposition", "attachment;filename=" + "Questions Report.csv");
response.Write(reportString);
return HttpStatusCode.OK;
}
这段代码肯定可以工作,我可以去URL提示下载。
$('.js-btn-download-content').click(function (event) {
var currentLanguage = getCulture();
var url = baseUrl + 'report/get/' + currentLanguage;
event.preventDefault();
$('.loadingContent-download').fadeIn(200);
$.ajax({
headers: {
Accept : "text/csv; charset=utf-8",
"Content-Type": "text/csv; charset=utf-8"
},
url: url,
dataType: "text/csv",
success: function (data) {
$('.loadingContent-download').fadeOut(200);
// Not sure about code below
//var xmlDoc = $.parseXML(data);
//var $xml = $(xmlDoc);
//var $title = $xml.find("200");
//if ($title) {
//$('.contentDownloaded-download p').html('Content donwloaded!');
//$('.contentDownloaded-download').show();
//} else {
//$('.contentDownloaded-download p').html('Download failed! Please try again.');
//$('.contentDownloaded-download').show();
//
}
});
$('.js-btn-confirm').click(function () {
$('.contentDownloaded-download').fadeOut(200);
});
});
正如你所看到的,这里是一些javaScript,我一直在应用程序中使用来处理一个OK被返回。但是,当该脚本触发时,浏览器不会下载该文件。什么好主意吗?
在你的Get(string id)方法中,返回HttpResponseMessage而不仅仅是HttpStatusCode。此外,ASP.net Web API不能确保HttpContext.Current.Response的状态(如果没有一些向导代码)。您可以这样做,将签名更改为Get(HttpRequestMessage request, string id),然后调用request。连接CreateResponse (statusCode、数据)。
相关文章:
- 将FormParams与Jersey和jQuery一起使用
- 存储数据的最佳方式是什么,以便与jquery一起使用
- 在使用 Django 静态文件时动态设置映像时,只有绝对路径才能与 jquery 一起使用
- 使一组对象与 jQuery 一起拖动
- 将(this)与动态内容jQuery一起使用
- 将页面Url与jQuery一起使用
- 如何找到元素'的onClick处理程序实际上是与jQuery一起添加的
- 400错误请求仅使用AngularJs,与jQuery一起使用
- 引导设置单选按钮与 jquery 一起检查
- 将 ajax 与 jQuery 一起使用 - URL 不被接受
- 如何将 fadeIn 与 css 属性更改 jquery 一起使用
- 我应该如何初始化这个变量以与jQuery一起使用
- 单击按钮更改按钮上的 ID 值,单击新 ID 更改回原始 ID 与 Jquery 一起使用
- 将其与伪选择器 jquery 一起使用
- 使类在由 jquery 更新后与 jquery 一起使用
- 如何引用要与 HTML 和 jQuery 一起使用的 XML 文件/数据
- 如何将foreach循环与JQuery一起使用
- 将 $_GET 与 Jquery 一起使用
- 如何将表与 jquery 一起使用
- 将.html与JQuery一起使用,不会将数组中的所有项发布到html