asp.net-mvc - 在 MVC 中捕获 form.submit() 响应

标签 asp.net-mvc model-view-controller

当提交表单(form.submit()并且没有ajax)时,是否有任何方法可以检测响应是否返回(假设未加载新页面)。我实际上从 Controller 返回一个文件而不是一个新 View 。

查看:

<% using (Html.BeginForm()){%>
   ....
   <input id="submitsearch" type="submit" value="DownloadFile" name="SubmitButton" />
<%} %>

Controller :

return File(FileContent, "text/plain", Filename);

基本上我想要发生的是,当用户单击提交时,我显示一个加载图标,当出现下载弹出窗口时,我想删除加载图标。

所以我实际上不需要读取响应,而只是知道响应何时返回,以便我可以删除加载图标。

限制是我不能使用 ajax 调用来提交页面。

干杯。

最佳答案

您可以使用我称之为cookie轮询的技术:

<% using (Html.BeginForm("Download", "Home")) { %>
    <%= Html.Hidden("downloadToken", DateTime.Now.Ticks) %>
    <input type="submit" value="Download" />
<% } %>

<script src="<%= Url.Content("~/Scripts/jquery.cookie.js") %>" type="text/javascript"></script>
<script type="text/javascript">
    $('form').submit(function () {
        // We start a download => show some progress indicator here
        $(':submit', this).val('Please wait while downloading...').attr('disabled', 'disabled');

        // start polling for the cookie every 500ms
        var fileDownloadCheckTimer = window.setInterval(function () {
            var cookieValue = $.cookie('fileDownloadToken');
            var token = $('#downloadToken').val();
            if (cookieValue == token) {
                // The download has finished => remove the progress indicator
                $(':submit', $('form')).val('Download').removeAttr('disabled');

                // remove the cookie
                $.cookie('fileDownloadToken', null);

                // stop polling
                window.clearInterval(fileDownloadCheckTimer);
            }
        }, 500);
    });
</script>

以及 Controller 操作内部:

public ActionResult Download(string downloadToken)
{
    // Simulate a slow download
    Thread.Sleep(5000);
    var cookie = new HttpCookie("fileDownloadToken", downloadToken);
    // set the cookie with the proper value
    Response.AppendCookie(cookie);
    return File(Encoding.UTF8.GetBytes("foo bar"), "text/plain", "foo.txt");
}

关于asp.net-mvc - 在 MVC 中捕获 form.submit() 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6531005/

相关文章:

asp.net-mvc - 将 @Html.DisplayNameFor() 与 PagedList 一起使用

model-view-controller - Telerik MVC网格-跨越所有页脚单元

php - 如何为mvc crud网站创建动态更新功能

php - 当我使用 CakeDC/users 插件时不显示用户名

javascript - 将 $.ajax() 中的数组传递给 ajax 请求到 Controller Spring mvc

c# - 使用 bootstrap 3 在 mvc 表单中的同一行中显示查找文本框和 2 个下拉列表

asp.net-mvc - 显示模板未用于界面

c# - 在 C# MVC 中的单个 Bundle 中添加多个 Bundle

.net - 连接cshtml文件中的字符串

ruby-on-rails - #<Micropost::ActiveRecord_Associations_CollectionProxy:0x007ffc26104288> 的 MembersController#index 未定义方法 `total_pages' 中的 NoMethodError