Error message 0x800a1391: ASPX C# page encountering postback due to JavaScript timeout issue

Experience the following JS code showcasing remaining time, however, encountering a postback when resetting the timer by selecting the Yes button (aspx button). Consequently, if the timing is visible on screen and you click Yes, it will clear the gridview on the main page. Plus, if the primary modal pop-up is open, it will close unexpectedly, causing the user to lose any unsaved content. Any strategies for adjusting this to prevent postback when hitting yes? Alternatively, do you have better recommendations?

Snippet:

    function SessionExpireAlert(timeout) {
    var seconds = timeout / 1000;
    document.getElementsByName("secondsIdle").innerHTML = seconds;
    document.getElementsByName("seconds").innerHTML = seconds;
    setInterval(function () {
        seconds--;
        document.getElementById("seconds").innerHTML = seconds;
        document.getElementById("secondsIdle").innerHTML = seconds;
    }, 1000);
    setTimeout(function () {
        //Show Popup before 20 seconds of timeout.
        $find("mpeTimeout").show();
    }, timeout - 20 * 1000);
    setTimeout(function () {
        window.location = "Login.aspx";
    }, timeout);
};
function ResetSession() {
    //Redirect to refresh Session.
    window.location = window.location.href;
}

Resources referenced: How to programatically reset the session time without page refreshing in ASP.Net Display Session Timeout message before Session expires in ASP.Net

Answer №1

I discovered an improved solution that I merged with the initial one. Below is the revised JS code:

    var interval;
function SessionExpireAlert(timeout) {
    clearInterval(interval);
    var seconds = timeout / 1000;
    document.getElementById("seconds").innerHTML = seconds;
    document.getElementById("secondsIdle").innerHTML = seconds;
    interval = setInterval(function () {
        seconds--;
        document.getElementById("seconds").innerHTML = seconds;
        document.getElementById("secondsIdle").innerHTML = seconds;

    }, 1000);

    setTimeout(function () {
        //Display Popup before 50 seconds of timeout.
        $find("mpeTimeout").show();
    }, timeout - 50 * 1000);
    
    setTimeout(function () {
        window.location = "Login.aspx";
    }, timeout);
};
function ResetSession() {
    PageMethods.ResetSession(OnSuccess);
    return false;
}
function OnSuccess(response, userContext, methodName) {
    SessionExpireAlert(response);
}

Here's the ASPX code snippet:

<%-- FOR TIME OUT --%>

        <script type="text/javascript" src="js/timeOutScript.js"></script>
        <h3>Session Idle:&nbsp;<span id="secondsIdle"></span>&nbsp;seconds.</h3>
        <asp:LinkButton ID="lnkFake3" runat="server" />
        <ajax:ModalPopupExtender ID="mpeTimeout" BehaviorID ="mpeTimeout" runat="server" PopupControlID="pnlPopupmpeTimeout" TargetControlID="lnkFake3"
            OkControlID="btnYes" CancelControlID="btnNo" BackgroundCssClass="modalBackground3" OnOkScript = "ResetSession()">
        </ajax:ModalPopupExtender>
        <asp:Panel ID="pnlPopupmpeTimeout" runat="server" CssClass="modalPopup3" Style="display: none">
            <div class="header">
                Session Expiring!
            </div>
            <div class="body">
                Your Session will expire in&nbsp;<span id="seconds"></span>&nbsp;seconds.<br />
                Do you want to continue?
            </div>
            <div class="footer" align="right">
                <asp:Button ID="btnYes" runat="server" Text="Yes" CssClass="yes3" OnClick="btnYes_Click" OnClientClick="return ResetSession()"/>
                <asp:Button ID="btnNo" runat="server" Text="No" CssClass="no3" OnClick="btnNo_Click"/> 
            </div>
        </asp:Panel>

        <%-- ENDS TIME OUT --%gt;

Lastly, here's the C# backend code:

protected void Page_Load(object sender, EventArgs e)
{
    Response.Cache.SetCacheability(HttpCacheability.NoCache);

    lbUserID.Text = Context.User.Identity.Name;
    UpdateProgress1.AssociatedUpdatePanelID = UpdatePanel1.UniqueID;
    lbLocalTime.Text = DateTime.Now.ToLongDateString();
    if (!this.IsPostBack)
    {

        /*FOR TIMEOUT PURPOSE*/

        Session["Reset"] = true;
        Configuration config = WebConfigurationManager.OpenWebConfiguration("~/Web.Config");
        SessionStateSection section = (SessionStateSection)config.GetSection("system.web/sessionState");
        int timeout = GetSessionTimeout();
        ClientScript.RegisterStartupScript(this.GetType(), "SessionAlert", "SessionExpireAlert(" + timeout + ");", true);

        /*ENDS TIME OUT*/

    }

}

[WebMethod(EnableSession = true)]
public static int ResetSession()
{
    HttpContext.Current.Session["Reset"] = true;
    int timeout = GetSessionTimeout();
    return timeout;
}

private static int GetSessionTimeout()
{
    Configuration config = WebConfigurationManager.OpenWebConfiguration("~/Web.Config");
    SessionStateSection section = (SessionStateSection)config.GetSection("system.web/sessionState");
    return Convert.ToInt32(section.Timeout.TotalMinutes * 1000 * 60);
}

Error Tag: 0x800a1391 – There was a JavaScript runtime error: ‘PageMethods’ is undefined.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Choosing a component without an identifier

Trying to select an element from a webpage can be a bit tricky. After inserting a control into the page and needing to set some values for an element inside the control at pageload from C# code, you may encounter issues with id prefixes being appended due ...

Tracking locations in real time with the AR.js framework

Is it possible to utilize the AR.js web framework for creating an Augmented Reality web app that helps users navigate from their current location to a specific destination with coordinates (lat, long)? I am looking to have it compatible with Chrome/Safari ...

PhongMaterial designed specifically for rendering InstancedBufferGeometry

I am working on creating a scene with thousands of simple meshes, and I decided to implement InstancedBufferGeometry for better performance. Most of my code is based on the example provided here: Although instancing works well, it seems to only function p ...

The issue persists with the event listener not responding to input key

Can the Keycode that is pressed during the firing of addEventListener input be retrieved? <p contentEditable="true" id="newTask">New task</p> document.getElementById("newTask").addEventListener("input" ...

Assistance with JavaScript Regular Expressions for formatting BBCode

A few weeks ago, I stumbled upon this regex expression: /([\r\n])|(?:\[([a-z\*]{1,16})(?:=([^\x00-\x1F"'\(\)<>\[\]]{1,256}))?\])|(?:\[\/([a-z]{1,16})\])/ig It's designe ...

Transferring scope between pages without the need for an angular service definition

Looking to open a new JSP page while passing the $scope in order to utilize an array response generated in the initial page. Example from test.js file: (function() { 'use strict'; angular .module('test', []) .control ...

Tips for triggering animation only when the element is in the viewport

I'm currently developing in React and facing a challenge where I need to trigger a fade animation for an element only when it becomes visible on the screen. The issue is that right now, the animation plays as soon as the page loads, which defeats the ...

Update the dropdown field selection to the color #333 with the help of javascript

I am facing an issue with a dropdown field that has placeholder text and options to select. Initially, both the placeholder text and the options were in color #333. However, I managed to change the color of the placeholder text to light grey using the foll ...

What is the best way to use AngularJS filters to arrange time?

Currently, I have a timer that is counting down from a user-set value. Users input a number representing minutes, which is then converted to milliseconds by multiplying it by 1000 * 60. The timer then decrements this number as it counts down. My goal is t ...

Using colored circles in ASP Dropdownlist ListItems (without jQuery): A step-by-step guide

Objective: To create a Dropdown list that displays a green circle if someone's Availability is True, and a red circle if someone's Availability is False. Note: The task needs to be accomplished without the use of jQuery, as it is restricted in t ...

What is the best method to deserialize XML with a specific structure into its corresponding POCO model using C#?

I have a unique web service that provides me with an XML result structured as follows: <details> <detail> <attribute>type</attribute> <value>Example</value> </detail> <detail> ...

Column 'addresscod_address' is not recognized in the 'field list - C#'

Hey guys, I recently added an "address" table to my database to store user address information because my existing "person" table was getting too cluttered. Now I'm facing some relationship issues that require me to reorganize my code. Here are the re ...

Alter the truth value of an item contained within an array

Embarking on my JavaScript journey, so please bear with me as I'm just getting started :) I am working on a small app where the images on the left side are stored in an array. When a user clicks on one of them, I want to change its height and also tog ...

Guide on utilizing the print feature in C# Selenium with Chrome driver

On my website, there is a print option that I want to activate. <a href="https://crim.brib.pk/RenderReport_Version2.aspx??Product_Id=MjgwMQ%3d%3d-J2XNpfmNU8Q%3d&amp;RUID=MTEwMDI0NTAwMTU%3d-rBg0P40kyho%3d&amp;FinalResult=T#" onclick="AlertandPr ...

Automating radio button selection in AngularJS: Let your code choose the option

In a form with two radio buttons, I am trying to set the first one as the default selection. <input type="radio" name="playlist" ng-value="myCtrl.cleanPlaylist" ng-model="myCtrl.playlistSelected"> Clean <input type="radio" name="playlist" ng-val ...

Query in SQL to retrieve numbers that are multiples of a specified value

To create a candlestick graph, I need to convert the following table: amount created_at updated_at 258 2019-10-17 01:45:17 2019-10-17 01:45:17 186 2019-10-17 01:45:17 2019-10-17 01:45:17 122 2019-10-17 01:46:31 2019-1 ...

Can .ForEach be utilized with the contents of a Dictionary?

After switching a collection from List to Dictionary, I noticed that I need to use foreach() instead of .ForEach() when iterating through it - whether I'm going through the Dictionary itself or Dictionary.Values. It's not a major issue, but I ha ...

Navigating through JSON properties in C# using loops

The JSON string I am receiving is a part of the product specifications. It contains data representing the Header called "General" and key-value pairs within it. I want to avoid hardcoding specific properties like General and Display Features so that I can ...

Unable to trigger Bootstrap 5 Modal using ASP.NET Code-behind

I have searched through numerous discussions on this topic, but I have not yet come across a solution that works. I am working on an ASP.NET web application project and I want to utilize a Bootstrap 5 modal to show messages when users need to make correcti ...

Silverlight error - the operation cannot be executed on a relative URI

I am a beginner in developing silverlight applications and have recently created a web service in my asp.net project. However, I encountered an error when trying to connect to it through my silverlight project: "the operation is not supported for a relati ...