我正试图找到一种方法来保持我的会话活着当Controller花了很长时间才能回来结果。单击按钮时我的Javascript如下所示:
function OnClick(s, e) {
positionDate = ReportingPositionDate.GetDate().toDateString();
if (true) {
$.ajax({
type: "POST",
url: "@Url.Action("DataFileUpload", "ImportData")",
data: JSON.stringify({ positionDate: positionDate }),
dataType: "text",
contentType: "application/json; charset=utf-8",
beforeSend: function () { lpImport.Show(); },
success: function (msg) {
debugger;
ImportDataGridView.PerformCallback();
ImportSuccessMessage.SetVisible(true);
ImportSuccessMessage.SetText(msg);
lpImport.Hide();
},
Error: function (xhr) {
alert(xhr)
ImportDataGridView.PerformCallback();
}
});
}
}
在我获得成功之前基本上会话超时。我想默默地保持会话活着。 谢谢大家。
答案 0 :(得分:0)
我在网上搜索了同样的内容。有回应,但他们是不正确的。 我最终能够调整其中一个,这就是结果:
- 创建一个asp.net mvc应用程序; 将以下内容添加到家庭控制器:
[HttpPost]
public JsonResult KeepSessionAlive()
{
return new JsonResult { Data = "Postback " + on " + DateTime.Now};
}
----将以下内容添加到index.cshtml:
<div id="myDiv"></div>
@section scripts{
<script src="~/SessionUpdater.js"></script>
<script type="text/javascript">
SessionUpdater.Setup('@Url.Action("KeepSessionAlive","Home")');
</script>
} - 引用以下js文件[除了引用jquery]
SessionUpdater = (function () {
var clientMovedSinceLastTimeout = false;
var keepSessionAliveUrl = null;
//var timeout = 5 * 1000 * 60; // 5 minutes
var timeout = 15000; // 15 seconds for testing
function setupSessionUpdater(actionUrl) {
// store local value
keepSessionAliveUrl = actionUrl;
// alert(actionUrl);
// setup handlers
listenForChanges();
// start timeout - it'll run after n minutes
checkToKeepSessionAlive();
}
function listenForChanges() {
$("body").on("mousemove keydown", function () {
clientMovedSinceLastTimeout = true;
});
}
// fires every n minutes - if there's been movement ping server and restart timer
function checkToKeepSessionAlive() {
setTimeout(function () { keepSessionAlive(); }, timeout);
}
function keepSessionAlive() {
// if we've had any movement since last run, ping the server
if (!clientMovedSinceLastTimeout && keepSessionAliveUrl != null) {
$.ajax({
type: "POST",
url: keepSessionAliveUrl,
success: function (data) {
$('#span').text(data);
$('#myDiv').append('<br/>' + data);
// reset movement flag
clientMovedSinceLastTimeout = false;
// start listening for changes again
listenForChanges();
// restart timeout to check again in n minutes
checkToKeepSessionAlive();
},
error: function (data) {
alert("ERROR");
console.log("Error posting to " & keepSessionAliveUrl);
}
});
}
else {
clientMovedSinceLastTimeout = false;
listenForChanges();
checkToKeepSessionAlive();
}
}
// export setup method
return {
Setup: setupSessionUpdater
};
})();