我最近要實現這種功能,我自己的,發現這個問題,並鏈接到傑西·泰伯的博客非常有幫助,所以我想我會使用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」中任何元素的任何子元素。