Search code examples
.nettimeoutpostbacksession-variablestabbed-browsing

Session Variable Mismatch Between Postback


I'm storing a session variable that I use to pass as a parameter for various data access calls. This variable is set when the session is first created, and it can be changed by the user depending on what resources they have access to. For instance, when the user first logs in their default session value might be set to "1". In the top corner of the page is a dropdownlist of all options they have access to and changing this changes the session variable... 1, 2, 3, 4... etc.

The problem is that this session variable may change between postbacks due to one of the following reasons:

  1. Session Timeout, causes the session to recreate itself with the default value of 1
  2. User opens two tabs/browser windows and changes it on one tab, then switches back to the other where the page rendered using "1" for the value

This causes the controls on the page to become "stale" and postbacks don't behave correctly. A button click event that relied on the session variable in its event handler may not be the "intended" event, and the interface is misleading.

What I'd like to be able to do is determine if the session variable's value has changed between postbacks, and if it has redirect back to the same page causing it to re-render using the new session variable value, and giving the user a clear indication what each postback actually does.

Any ideas?


Solution

  • What I ended up doing was adding a HiddenField to my masterpage and then putting this in the code behind:

            if (!Page.IsPostBack)
            {
                //SelectedID comes from masterpage property (Session variable)
                hiddenField.Value = SelectedID.ToString();
    
                ...
            }
            else
            {
                int selectedId = Int32.Parse(hiddenField.Value);
                if (selectedId != SelectedID)
                {
                    Response.Redirect(Request.RawUrl);
                }
            }