Hi,
I have a requirement to use global variable in MVC application, which is created using the below code. This valirable is assigned at the login time and is cleared at the time of logout. By mistake if we close the whole browser, then the variable is holding the value at the time of login. Is there any way to identify if the browser or tab is closed for making null to the variable
public static class GlobalVariable
{
static string _Id;
public static string _ID
{
get
{
return _Id;
}
set
{
_Id = value;
}
}
Aman GuptaPosted Sep 11, 2024, 7:44 AM
Hi Anu,
In your case, since you're working with an MVC application and need to clear a global variable when the browser or tab is closed, the key is to detect when the browser or tab is being closed and then clear the value. Here's a solution using JavaScript and server-side calls to address this:
Steps:
Example:
1. JavaScript to Detect Tab Close
You can add this script in your view (e.g., Layout.cshtml):
2. Controller Action to Clear Global Variable: Create a method in your controller to handle clearing the global variable:
Hope this will help you Anu.
Jignesh KumarPosted Sep 11, 2024, 9:01 AM
Hello,
you can achieve via javascript and api endpoint to clear all global variable there,
AnuPosted Sep 10, 2024, 1:08 PM
Thanks Jignesh for your suggestion.
I am already using session in the project, but for some specific requirement I have to use the global variable with the session. Can you suggest a way to clear global variable on browser window close
Jignesh KumarPosted Sep 10, 2024, 12:08 PM
Hello Anu,
You can use session management in MVC core,
While static global variables are not ideal for managing user-specific data in an ASP.NET Core MVC application, session state, offer more reliable ways to handle user-specific information and manage its lifecycle.
You can use in Login and Logout method as below,