-- Create an asp.net mvc app; add the following to the home controller:
[HttpPost]
public JsonResult KeepSessionAlive()
{
return new JsonResult { Data = "Postback " + on " + DateTime.Now};
}
----Add the following to index.cshtml:
<div id="myDiv"></div>
@section scripts{
<script src="~/SessionUpdater.js"></script>
<script type="text/javascript">
SessionUpdater.Setup('@Url.Action("KeepSessionAlive","Home")');
</script>
} -- reference the following js file [in addition to referencing 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
};
})();