ASP.net MVC返回文件和重定向 [英] ASP.net MVC Return File and Redirect
本文介绍了ASP.net MVC返回文件和重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个控制器返回csv文件。我想这已经显示后,即返回到主视图重定向到一个动作。
控制器逻辑如下所示:
公众的ActionResult DownloadCSV(字符串文件名)
{
字符串的csv;
使用(StreamReader的SR =新的StreamReader(文件名))
{
CSV = sr.ReadToEnd();
}
返回文件(新System.Text.UTF8Encoding()GetBytes会(CSV),文/ CSV,Export.csv);
}
解决方案
短的版本是,你不能强迫一个文件下载和HTTP,因为限制了同样的动作重定向。但你可以通过打开文件下载动作强制下载 window.open
。
示例:
< A HREF =动作/ RedirectPage数据文件=动作/ DownloadCVS级=文件下载>下载文件< / A><脚本>
$(函数(){
$('a.file下载')。点击(函数(){
window.open($(本)。数据('文件'));
});
});
< / SCRIPT>
在这种情况下,我使用HTML5的属性,但你不局限于做这种方式。
I have a controller that returns csv file. I want to redirect to an action after this has displayed, i.e. return to the home view. The controller logic is shown below:
public ActionResult DownloadCSV(string fileName)
{
string csv;
using (StreamReader sr = new StreamReader(fileName))
{
csv = sr.ReadToEnd();
}
return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "Export.csv");
}
解决方案
The short version is that you can't force a file download and redirect in the same action because of HTTP limitations. But you could force the download by opening the file-download action using window.open
.
Example:
<a href="Action/RedirectPage" data-file="Action/DownloadCVS" class="file-download">Download File</a>
<script>
$(function() {
$('a.file-download').click(function() {
window.open($(this).data('file'));
});
});
</script>
In this case I used HTML5 attributes, but you're not limited to do it in this way.
这篇关于ASP.net MVC返回文件和重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文