2009-06-08 20 views
3

我有一個ASP.NET MVC表單,它返回一個報告作爲文件(...)的結果。這意味着在文件下載被觸發後,瀏覽器保持在當前頁面上。使用jQuery,我想禁用提交按鈕,然後在文件返回後重新啓用它。 我的代碼已經禁用了按鈕,但是,我無法找到一個事件掛鉤到文件返回後觸發。jQuery在文件結果返回後重新啓用表單

這是我到目前爲止有:

$(document).ready(function() { 
     $("#downloadForm").submit(function() { 
      $("#cmdSubmit").attr("disabled", "disabled"); 
      $("#uiProgress").show(); 
     }); 
    }); 

我可以添加到這個什麼觸發當表單提交的回報?

回答

3

您可能必須複雜化該過程:不要從文章返回文件,而是讓#downloadForm發佈AJAX請求,該請求會將URL返回到文件。收到響應後,您可以重新啓用您的按鈕並將document.location設置爲返回的URL。

1

我最近要實現這種功能,我自己的,發現這個問題,並鏈接到傑西·泰伯的博客非常有幫助,所以我想我會使用ASP.NET MVC分享我在這裏實現。

基本理論是當您提交表單時,將令牌傳遞給控制器​​,並且控制器在發生下載時在響應中設置具有該值的cookie。

(很抱歉沒能VB.NET)

屬性添加到您的模型來存儲令牌:

Public Property DownloadToken As String 

然後設置在響應中的Cookie返回結果之前:

If Response.Cookies("MyFileDownloadToken") Is Nothing Then 
    Dim cookie As New HttpCookie("MyFileDownloadToken", ParameterModel.DownloadToken) 

    Response.Cookies.Add(cookie) 
Else 
    Response.Cookies("MyFileDownloadToken").Value = ParameterModel.DownloadToken 
End If 

將令牌屬性添加爲窗體上的隱藏字段:

@Html.HiddenFor(Function(m) m.DownloadToken) 

然後我們可以使用JavaScript來控制sumbit按鈕和jQuery Cookie插件來獲取和設置cookie的值。

var fileDownloadChecker; 

$(function() 
{ 
    $("#MyForm").submit(function() 
    { 
     $(".validation-summary-errors").empty(); //Clear any validation errors from a previous failed form submission 
     PreventResubmission(); 
    }); 

    $("#submitButton").prop("disabled", false); 
} 

function PreventResubmission() 
{ 
    //Use the current time as a unique token that we can check for in the response 
    var token = new Date().getTime(); 

    //Set the token so that it is passed through to the controller 
    $("#DownloadToken").val(token); 

    //Prevent the user from resubmitting the form 
    $("#submitButton").prop("disabled", true); 
    $("#submitButton").val("Running..."); 

    //Check once a second for the token in the response 
    fileDownloadChecker = window.setInterval(function() 
    { 
     var cookieValue = $.cookie("MyFileDownloadToken"); 

     if (cookieValue == token) 
     { 
      EnableFormSubmission(); 
     } 
    }, 1000); 
} 

function EnableFormSubmission() 
{ 
    //Stop checking for the token 
    window.clearInterval(fileDownloadChecker); 
    fileDownloadChecker = 0; 

    //Clear the hidden field 
    $("#DownloadToken").val(""); 

    //Clear the cookie that contains the token 
    $.cookie("MyFileDownloadToken", null, { path: "/" }); 

    //Enable the form submit button 
    $("#submitButton").prop("disabled", false); 
    $("#submitButton").val("Run"); 
} 

注意事項:

1)對的HttpCookie類和jQuery的Cookie的接口的默認路徑設置是不同的。默認情況下,HttpCookie是以根('/')創建的,而jQuery插件將根據當前路徑搜索(並設置)cookie。如果讀取一個cookie,它會後退並查看其他路徑。所以我們至少在清除cookie時指定路徑。 (GOT進入的情況下的代碼會工作一次,但隨後會失敗,因爲它會發現該cookie在當前路徑並始終將返回值)

2)我已經添加了一條線,使提交按鈕時,頁面加載,因爲如果頁面在運行階段因任何原因而刷新,它將持續按鈕的「禁用」狀態。3)如果你的頁面與我的頁面類似,它會顯示模型驗證錯誤,但是頁面在成功提交後永遠不會刷新,所以以前的驗證錯誤仍然會顯示在表單上。我在表單的提交事件處理程序中添加了一行以清除類「.validation-summary-errors」中任何元素的任何子元素。