c# - 处理返回的 ASP.NET MVC FileResult

标签 c# javascript asp.net-mvc asp.net-mvc-3 file

在我的 Controller 中,我有一个 ActionResult 它返回一个文件。

[HttpPost]
public ActionResult ExportCSV(ReportResultViewModel model)   
{     
    var content = "hello,world";
    return File(Encoding.UTF8.GetBytes(content),"text/csv","export.csv");
}

在我看来,当我发布到此 ActionResult 时,我会显示一个模式“请稍候”。

<!--modal-->
<div class="modal fade" id="pleaseWaitDialog" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content" style="background: #EBF3EB;">
            <div class="modal-header">
                <h1>Please wait...</h1>
            </div>
            <div class="modal-body">
                <div id="loader"></div>
            </div>
       </div>
    </div>
</div>
@using (Html.BeginForm("ExportCSV", "Reporting", FormMethod.Post, new { name = "back", id = "back", style = "width:100%" }))
{
     @Html.HiddenFor(m => m.A)
     @Html.HiddenFor(m => m.LOT)
     @Html.HiddenFor(m => m.OF)
     @Html.HiddenFor(m => m.THINGS)

     <input type="submit" data-toggle="modal" data-target="#pleaseWaitDialog" value="Export CSV" style="width: 100%; background: #fff" class="btn btn-default"  />
}

我想在文件最终返回页面时隐藏它。

有没有办法在文件到达时检测客户端(可能使用 JavaScript),以便我可以隐藏模式?

最佳答案

我想你想要的是 jQuery 文件下载 http://jqueryfiledownload.apphb.com/在您的 View 中添加对 jquery ui 库和文件下载库的引用,然后添加脚本标记。

<script type="text/javascript">

$(function () {
    var $pleaseWaitDialog= $("#pleaseWaitDialog"); 

    $(document).on("submit", "#back", function (e) {

        $pleaseWaitDialog.dialog({ modal: true });

        $.fileDownload($(this).prop('action'), {
            httpMethod: 'POST',
            data: $(this).serialize,
            successCallback: function (url) {
                $pleaseWaitDialog.dialog('close');
            },
            failCallback: function (responseHtml, url) {
                $pleaseWaitDialog.dialog('close');
            }
        });
        e.preventDefault; //otherwise normal form submit will occur 
    });
});
</script>

这将执行的操作是,当单击 #ExportCSV 表单的提交按钮时,它将显示 #pleaseWaitDialog 标记的模式对话框。然后使用 fileDownload 插件,它将向表单的操作 URL 发送一个帖子。提交的数据来自 $(this).serialize 调用。当文件成功下载或调用失败时,它只是关闭对话框。

关于c# - 处理返回的 ASP.NET MVC FileResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24547695/

相关文章:

c# - WIQL : How to get the content of a field of a work item returned by a query

c# - 未处理的异常后终止应用程序

javascript - 在决定如何将回调传递给 addEventListener 时,我应该考虑什么?

javascript - 使用 AJAX 将 JSON 标签加载到 Select2

c# - Orderby() 没有正确排序数字 c#

c# - 翻译源代码中的注释和区域名称

javascript - 渲染图表后,从图表对象更改 Highcharts 工具提示格式化程序

c# - 需要调用从 View 返回字符串值的 Controller 方法

c# - 在 OnActionExecuting 中重定向不起作用

c# - WPF Key枚举有什么解释吗?