Check Session Status From Client Side Using Ajax In ASP.NET MVC

Introduction

This article explains about session and how to check session status on the client side using Ajax in ASP.NET MVC.

Definition

The session is a server-side variable. It is used to store and retrieve from any page at the current user level.

Problem in Session when used in jQuery

Session value can be accessed in Javascript and jQuery. If we update or change the session value on the server side, it is not affected in JavaScript and jQuery. Session maintains the value which value is stored the first time in jQuery and JavaScript. If the session times out values automatically are removed on the server side but the client side is not removed so in this situation session is not working correctly or it makes the wrong result.

In web.config assigned session times out in one minute.

Assigned session

Step 1. Run the application then enter username and password.

Run the application

Step 2. If the password and username are correct then it redirects to Demo Page. When clicking the Redirect button at that time it redirects to another page. While a button click is needed to check session status, if the session is not null redirect to any other required page otherwise redirect to the login page.

The first time the session is true it redirected to the Check Session Page. On the web. config file assigned session time out one minute.

 Check Session Page

Step 3. Again click the Redirect button after one minute. While clicking the redirect button after one minute, now session value is null because the session times out again so go same page does not go to the login page.

Login page

Here we click the Redirect button each time the session value is true, because once we assign the session value in JavaScript or jQuery it's again not updated, so each time it's the session value that is assigned the first time.

This is the problem in Jquery and Javascript.

Solution

In ASP.Net MVC we use Ajax each time to check the session status from the client side to the server side, that is from JQuery to the controller. For example when redirecting from one page to another page on a button click check session status using Ajax.

Step 1. Add a class in a model for checking sessions from the client side as follows.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ClientSideSession.Models
{
    public class sessionClass
    {
        public bool sessionValue { set; get; }
    }
}

Step 2. Add JSON method in the controller for checking session from the client side with the help of the “sessionclass” class.

public JsonResult checkSession()
{
    sessionClass s = new sessionClass();
    if (Session["UserName"] != null)
    {
        s.sessionValue = true;
    }
    else
    {
        s.sessionValue = false;
    }
    return Json(s, JsonRequestBehavior.AllowGet);
}

Step 3. In button click we need to check session status. While button clicking with the help of Ajax check session status in checkSession method. Here if the session value is not null then assign the value true in sessionClass’s prosperities otherwise assign the value false.

<script>
    $("#btnClick").click(function () {
        $.ajax({
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            url: '/Home/checkSession',
            data: '{}',
            success: function (data) {
                alert(data.sessionValue);
                if (data.sessionValue == true) {
                    location.href = "/Home/Demo";
                } else {
                    location.href = "/Home/Login";
                }
            },
            error: function (xhr) {
                alert('error');
            }
        });
    });
</script>

In the Button click event, we need to add above the code each time and check the session status from the client side to the server side. Wherever we need session status on the client side, could follow like above code.

Conclusion

I hope this step-by-step method helps you how to check the session status from the client side to the server side using jQuery in ASP.NET MVC.

Read more articles on ASP.NET.


Similar Articles