Did*_*xis 5 .net c# asp.net jquery asp.net-mvc-3
我正在尝试将一个数组/ IEnumerable Guids传递给MVC'GET'方法,如下所示:
[HttpGet]
public ActionResult ZipResults(IEnumerable<Guid> ids)
{
using(var zip = new Zip())
{
foreach(var id in ids)
{
var stream = GetDataStream(id);
zip.AddEntry("filename.txt", stream);
}
}
var outputStream = new MemoryStream();
zip.Save(outputStream);
return FileStreamResult(outputStream, "application/octet-stream"){
FileDownloadName = "Results.zip" };
}
Run Code Online (Sandbox Code Playgroud)
我的javascript看起来像这样:
$('the-button').click(function(){
// 1. Get the guids from a table and add to javascript array (works fine)
// 2. Grey-out screen and show processing indicator (works fine)
// 3. This is how I'm calling the "ZipResults" action:
$.ajax({
url: '@Url.Action("ZipResults", "TheController")',
type: 'GET',
data: $.toJSON({ ids: _ids }),
dataType: 'json',
contentType: 'application/json;charset=utf-8',
traditional: true,
success: function(){
// Undo the grey-out, and remove processing indicator
},
error: function(){
}
});
});
Run Code Online (Sandbox Code Playgroud)
我的期望是这将弹出浏览器上的下载对话框.实际上,传递给控制器的javascript数组是空的(在服务器端,它在客户端正常工作).此外,这适用于'POST',但是,这种方式使用'POST'方法不会强制下载对话框...
打开建议:)
您应该避免使用GET发送JSON请求.试试这样:
var _ids = [
'e2845bd4-9b3c-4342-bdd5-caa992450cb9',
'566ddb9d-4337-4ed7-b1b3-51ff227ca96c',
'25bc7095-a12b-4b30-aabe-1ee0ac199594'
];
$.ajax({
url: '@Url.Action("ZipResults", "TheController")',
type: 'GET',
data: { ids: _ids },
dataType: 'json',
traditional: true,
success: function() {
// Undo the grey-out, and remove processing indicator
},
error: function() {
}
});
Run Code Online (Sandbox Code Playgroud)
这就是说,我看到你正在调用一些控制器动作,它返回一个要下载的文件流.你根本不应该使用AJAX来做到这一点.这样做的原因是,在你的成功回调中,你将获得ZIP文件的内容,但是你用它做的并不多.你不能将它保存到客户端计算机,你不能提示用户选择一个保存位置,你几乎被破坏了.
因此,如果要下载文件,则不会调用AJAX.你可以使用一个简单的锚点:
@Html.ActionLink("download zip", "ZipResults", "TheController", null, new { id = "download" })
Run Code Online (Sandbox Code Playgroud)
然后:
$(function() {
$('#download').click(function() {
var _ids = [
'e2845bd4-9b3c-4342-bdd5-caa992450cb9',
'566ddb9d-4337-4ed7-b1b3-51ff227ca96c',
'25bc7095-a12b-4b30-aabe-1ee0ac199594'
];
var url = this.href;
for (var i = 0; i < _ids.length; i++) {
if (url.indexOf('?') > 0) {
url += '&ids=' + encodeURIComponent(_ids[i]);
} else {
url += '?ids=' + encodeURIComponent(_ids[i]);
}
}
window.location.href = url;
return false;
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5287 次 |
| 最近记录: |