Is it possible to show the remaining session time in View
in real-time when logged in ASP.NET MVC project? I didn't add any code to the question because I didn't come across any solution during my research.
Asked
Active
Viewed 1,532 times
1

George Sun
- 85
- 6
-
The way sessions work is any user action with the server is supposed to reset the session. So if you have, say, 20 minute sessions, at the time of any http request --that is, any C# code runs at all other than heartbeat/signalr stuff -- the session time remaining is **always** the full 20 minutes. So at this point what you're really doing is writing a javascript countdown timer for the amount of your session timeout. – Joel Coehoorn Dec 14 '21 at 22:29
-
I can set up a counter on login, but how can I share the counter value between different Views? In addition, the session duration can be changed via the **web.config** file. – George Sun Dec 14 '21 at 22:35
-
If the session time gets reset with each action, there would be no value to share between views. [Get value from web config](https://stackoverflow.com/a/4595323/1679220) – hijinxbassist Dec 15 '21 at 00:40
1 Answers
1
I would do this in 2 steps, first pass the timeout value using a partial, so it can be reused. For e.g. read it from your Web.Config etc
and pass it.
Then inside your view, you can add this script and adapt/modify the values.
@functions {
public int PopupShowDelay {
get { return 60000 * (Session.Timeout - 1); }
}
}
<script type="text/javascript">
window.SessionTimeout = (function() {
var _timeLeft, _popupTimer, _countDownTimer;
var stopTimers = function() {
window.clearTimeout(_popupTimer);
window.clearTimeout(_countDownTimer);
};
var updateCountDown = function() {
var min = Math.floor(_timeLeft / 60);
var sec = _timeLeft % 60;
if(sec < 10)
sec = "0" + sec;
document.getElementById("CountDownHolder").innerHTML = min + ":" + sec;
if(_timeLeft > 0) {
_timeLeft--;
_countDownTimer = window.setTimeout(updateCountDown, 1000);
} else {
window.location = "Home/TimeOutPage";
}
};
var showPopup = function() {
_timeLeft = 60;
updateCountDown();
ClientTimeoutPopup.Show();
};
var schedulePopup = function() {
stopTimers();
_popupTimer = window.setTimeout(showPopup, @PopupShowDelay);
};
var sendKeepAlive = function() {
stopTimers();
ClientTimeoutPopup.Hide();
SessionTimeout.schedulePopup();
};
return {
schedulePopup: schedulePopup,
sendKeepAlive: sendKeepAlive
};
})();
</script>
@using (Html.BeginForm()) {
<p>
A timeout warning popup will be shown every @(Session.Timeout - 1) min.
</p>
@Html.Partial("TimeoutPartial")
}

Transformer
- 6,963
- 2
- 26
- 52