Wednesday, 24 May 2017

How to pass data from one view to another in ASP.NET MVC

You may come across a situation where you may wish to pass data from one asp.net razor view to another. There are a number ways of doing the same.
1. Using Partial Views
One commonly used way to pass data from one view to another is you can create a dynamic anonymous object and pass it to the partial function
1
@Html.Partial("viewname", new {item1="value1", item2 = "value2"})

Now in your partial view, you can use dynamic keyword to access the data in the partial view. The view should look like

1
2
3
@model dynamic
<div>@Model.item1</div>
<div>@Model.item2</div>
2. Use TempData
This is useful when your partial view accepts model of another type or you wish to use any existing partial view and pass data to it. TempData uses an indexed dictionary with key and value to store the data.
So in your view where you wish to include the partial view, you write it like:

1
2
3
4
5
@{
TempData["item1"] = "value1";
TempData["item2"] = "value2";
}
@Html.Partial("viewname")
Note how we used string keys to define our data values. You can create as many keys as you want.
Note that if you add the same key again, it’ll overwrite the previous value.
Now in your partial view, you can use the data as:

1
2
3
4
5
@{
if(TempData["item1"] != null){
//use TempData["item1"] to retrieve the value
}
}
A null check before retrieval of data ensures that the Razor engine doesn’t throw any error in case no data has been passed.
Note that life of TempData  is only till the current request completes. It’s not available thereafter
3. Using Session Variables
The usage syntax of session variables is similar to TempData except that the lifetime of a session variable is for the entire browser session (or an expiration time of 20 minutes default).


 Happy Programming!!

Don’t forget to leave your feedback and comments below!

If you have any query mail me to Sujeet.bhujbal@gmail.com     

Regards
Sujeet Bhujbal
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------


Friday, 10 March 2017

Session Expiration Time out Popup using jquery

Session Expiration Time out Popup using jquery

Introduction


In this article, I will tell you how to create a cross-browser session expiration popup box using jQuery easily


Background


Session timeout is very much important in every project. There are so many articles already written for session timeout. Therefore, in this article I will tell you how to create use session timeout using jQuery easily. We can configure session timeout and after finishing this timing, user will receive notification like that, you need to logout to extend timeout.

Using the code


Part A: HTML Code

Part 1: Creating a Popup using Bootstrap

   To show session timeout popup we need two popups, one for showing session expire warning like “Your session will expire in -- seconds. Do you want to extend the session?” It will give three options
1.       OK to extend
2.       Cancel to close popup
3.       Logout Now to Logout


Please find below screenshot for it
















Second one is session expired message. This will redirect to logout page

Below is bootstrap UI of these 2 popups

<!--Start Show Session Expire Warning Popup here -->
    <div class="modal fade" id="session-expire-warning-modal" aria-hidden="true" data-keyboard="false" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">                 
                    <h4 class="modal-title">Session Expire Warning</h4>
                </div>
                <div class="modal-body">
                    Your session will expire in <span id="seconds-timer"></span> seconds. Do you want to extend the session?
                </div>
                <div class="modal-footer">
                    <button id="btnOk" type="button" class="btn btn-default" style="padding: 6px 12px; margin-bottom: 0; font-size: 14px; font-weight: normal; border: 1px solid transparent; border-radius: 4pxbackground-color: #428bca; color: #FFF;">Ok</button>
                    <button id="btnSessionExpiredCancelled" type="button" class="btn btn-default" data-dismiss="modal" style="padding: 6px 12px; margin-bottom: 0; font-size: 14px; font-weight: normal; border: 1px solid transparent; border-radius: 4px; background-color: #428bca; color: #FFF;">Cancel</button>
                    <button id="btnLogoutNow" type="button" class="btn btn-default" style="padding: 6px 12px; margin-bottom: 0; font-size: 14px; font-weight: normal; border: 1px solid transparent; border-radius: 4pxbackground-color: #428bca; color: #FFF;">Logout now</button>
                </div>
            </div>
        </div>
    </div>



    <!--End Show Session Expire Warning Popup here -->



    <!--Start Show Session Expire Popup here -->
    <div class="modal fade" id="session-expired-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Session Expired</h4>
                </div>
                <div class="modal-body">
                    Your session is expired.
                </div>
                <div class="modal-footer">
                    <button id="btnExpiredOk" onclick="sessionExpiredRedirect()" type="button" class="btn btn-primary" data-dismiss="modal" style="padding: 6px 12px; margin-bottom: 0; font-size: 14px; font-weight: normal; border: 1px solid transparent; border-radius: 4px; background-color: #428bca; color: #FFF;">Ok</button>
                </div>
            </div>
        </div>
    </div>


Part B: JavaScript Code


1.        Setting Server Ping Configuration:  
This configuration will always ping server to check session Alive or not
var sessServerAliveTime = 10 * 60 * 200;

     2.       . Setting session timeout configuration
 Here you can give configuration for session timeout

var sessionTimeout = 19 * 60000;

  • 3   Use of Local Storage

          Here we used localstorage for setting sessionSlide variable.

4.       Use of sessPingServer() Method
Here we used  sessPingServer Method for Ping to sever using Ajax Call. In code snippet, I commented my ajax pinging code.


      

Javascript Code Snippet


var sessServerAliveTime = 10 * 60 * 2;
var sessionTimeout = 2 * 60000;
var sessLastActivity;
var idleTimer, remainingTimer;
var isTimout = false;

var sess_intervalID, idleIntervalID;
var sess_lastActivity;
var timer;
var isIdleTimerOn = false;
localStorage.setItem('sessionSlide', 'isStarted');

function sessPingServer() {
    if (!isTimout) {
        //$.ajax({
        //    url: '/Admin/SessionTimeout',
        //    dataType: "json",
        //    async: false,
        //    type: "POST"
        //});

        return true;
    }
}

function sessServerAlive() {
    sess_intervalID = setInterval('sessPingServer()', sessServerAliveTime);
}

function initSessionMonitor() {
    $(document).bind('keypress.session', function (ed, e) {
        sessKeyPressed(ed, e);
    });
    $(document).bind('mousedown keydown', function (ed, e) {

        sessKeyPressed(ed, e);
    });
    sessServerAlive();
    startIdleTime();
}



$(window).scroll(function (e) {
    localStorage.setItem('sessionSlide', 'isStarted');
    startIdleTime();
});

function sessKeyPressed(ed, e) {
    var target = ed ? ed.target : window.event.srcElement;
    var sessionTarget = $(target).parents("#session-expire-warning-modal").length;

    if (sessionTarget != null && sessionTarget != undefined) {
        if (ed.target.id != "btnSessionExpiredCancelled" && ed.target.id != "btnSessionModal" && ed.currentTarget.activeElement.id != "session-expire-warning-modal" && ed.target.id != "btnExpiredOk"
             && ed.currentTarget.activeElement.className != "modal fade modal-overflow in" && ed.currentTarget.activeElement.className != 'modal-header'
    && sessionTarget != 1 && ed.target.id != "session-expire-warning-modal") {
            localStorage.setItem('sessionSlide', 'isStarted');
            startIdleTime();
        }
    }
}

function startIdleTime() {
    stopIdleTime();
    localStorage.setItem("sessIdleTimeCounter", $.now());
    idleIntervalID = setInterval('checkIdleTimeout()', 1000);
    isIdleTimerOn = false;
}

var sessionExpired = document.getElementById("session-expired-modal");
function sessionExpiredClicked(evt) {
    window.location = "Logout.html";
}





sessionExpired.addEventListener("click", sessionExpiredClicked, false);
function stopIdleTime() {
    clearInterval(idleIntervalID);
    clearInterval(remainingTimer);
}

function checkIdleTimeout() {
     // $('#sessionValue').val() * 60000;
    var idleTime = (parseInt(localStorage.getItem('sessIdleTimeCounter')) + (sessionTimeout)); 
    if ($.now() > idleTime + 60000) {
        $("#session-expire-warning-modal").modal('hide');
        $("#session-expired-modal").modal('show');
        clearInterval(sess_intervalID);
        clearInterval(idleIntervalID);

        $('.modal-backdrop').css("z-index", parseInt($('.modal-backdrop').css('z-index')) + 100);
        $("#session-expired-modal").css('z-index', 2000);
        $('#btnExpiredOk').css('background-color', '#428bca');
        $('#btnExpiredOk').css('color', '#fff');

        isTimout = true;

        sessLogOut();

    }
    else if ($.now() > idleTime) {
        ////var isDialogOpen = $("#session-expire-warning-modal").is(":visible");
        if (!isIdleTimerOn) {
            ////alert('Reached idle');
            localStorage.setItem('sessionSlide', false);
            countdownDisplay();

            $('.modal-backdrop').css("z-index", parseInt($('.modal-backdrop').css('z-index')) + 500);
            $('#session-expire-warning-modal').css('z-index', 1500);
            $('#btnOk').css('background-color', '#428bca');
            $('#btnOk').css('color', '#fff');
            $('#btnSessionExpiredCancelled').css('background-color', '#428bca');
            $('#btnSessionExpiredCancelled').css('color', '#fff');
            $('#btnLogoutNow').css('background-color', '#428bca');
            $('#btnLogoutNow').css('color', '#fff');

            $("#seconds-timer").empty();
            $("#session-expire-warning-modal").modal('show');


            isIdleTimerOn = true;
        }
    }
}

$("#btnSessionExpiredCancelled").click(function () {
    $('.modal-backdrop').css("z-index", parseInt($('.modal-backdrop').css('z-index')) - 500);
});

$("#btnOk").click(function () {
    $("#session-expire-warning-modal").modal('hide');
    $('.modal-backdrop').css("z-index", parseInt($('.modal-backdrop').css('z-index')) - 500);
    startIdleTime();
    clearInterval(remainingTimer);
    localStorage.setItem('sessionSlide', 'isStarted');
});

$("#btnLogoutNow").click(function () {
    localStorage.setItem('sessionSlide', 'loggedOut');
    window.location = "Logout.html";
    sessLogOut();
    $("#session-expired-modal").modal('hide');

});
$('#session-expired-modal').on('shown.bs.modal', function () {
    $("#session-expire-warning-modal").modal('hide');
    $(this).before($('.modal-backdrop'));
    $(this).css("z-index", parseInt($('.modal-backdrop').css('z-index')) + 1);
});

$("#session-expired-modal").on("hidden.bs.modal", function () {
    window.location = "Logout.html";
});
$('#session-expire-warning-modal').on('shown.bs.modal', function () {
    $("#session-expire-warning-modal").modal('show');
    $(this).before($('.modal-backdrop'));
    $(this).css("z-index", parseInt($('.modal-backdrop').css('z-index')) + 1);
});


function countdownDisplay() {

    var dialogDisplaySeconds = 60;

    remainingTimer = setInterval(function () {
        if (localStorage.getItem('sessionSlide') == "isStarted") {
            $("#session-expire-warning-modal").modal('hide');
            startIdleTime();
            clearInterval(remainingTimer);
        }
        else if (localStorage.getItem('sessionSlide') == "loggedOut") {         
            $("#session-expire-warning-modal").modal('hide');
            $("#session-expired-modal").modal('show');
        }
        else {

            $('#seconds-timer').html(dialogDisplaySeconds);
            dialogDisplaySeconds -= 1;
        }
    }
    , 1000);
};

function sessLogOut() {

window.location = "Logout.html";
   // $.ajax({
   //     url: 'Logout.html',
   //     dataType: "json",
  //      async: false,
  //      type: "POST"
 //   });

}


 Please download code for demo from this link. I already set two Minute timer for popup. After 1 minute it will show timeout confirmation message and after that session expire popup will show


 Happy Programming!!

Don’t forget to leave your feedback and comments below!

If you have any query mail me to Sujeet.bhujbal@gmail.com     

Regards
Sujeet Bhujbal
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------