【问题标题】:Capturing form.submit() response in MVC在 MVC 中捕获 form.submit() 响应
【发布时间】:2011-09-25 17:42:13
【问题描述】:

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

查看:

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

控制器:

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

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

所以我实际上不需要阅读响应,只需知道响应何时返回,这样我就可以删除加载图标。

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

干杯。

【问题讨论】:

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


    【解决方案1】:

    如果您不能使用 ajax,您可以只返回一个带有文件下载链接的视图。但是如果没有 ajax,你将不得不重新加载整个页面......

    【讨论】:

    • 您好,实际上,如果您返回文件,页面根本不会刷新。一切正常(即下载),我只需要知道何时删除加载图标。
    • 也许这会对你有所帮助:stackoverflow.com/questions/1218245/…
    【解决方案2】:

    你可以使用我称之为cookie polling的技术:

    <% 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>
    

    在控制器内部:

    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");
    }
    

    【讨论】:

      猜你喜欢
      • 2010-09-27
      • 1970-01-01
      • 2011-03-24
      • 1970-01-01
      • 1970-01-01
      • 2020-04-20
      • 2014-01-24
      • 2019-04-26
      • 1970-01-01
      相关资源
      最近更新 更多