Trigger a C# function upon the Ajax timer (counts down) hitting 0

I am facing a major issue with a simple task... I have an asp.net page with a Multiview containing two views.

In the first view, there is an ajax timer that counts down from 60 to 0. The time is displayed on a label within an updatepanel. I want to call a C# function that performs certain tasks and then switches to the next active view once the countdown reaches zero.

How can I achieve this?

I attempted to check in the Timer_tick event if the seconds reach 0 and called the function, but it did not work. I also tried setting Timer1.Enabled = false, but that didn't work either.

I believe I need to use JavaScript, but I am unfamiliar with how and where to implement it. I have no knowledge of Javascript yet.

This is my Timer_Tick event (The time displayed on the label functions properly)

  protected void Timer1_Tick(object sender, EventArgs e)
    {
        Test t = (Test)Session["SelectedTest"];

        if (t.Remaining.Minute == 0 && t.Remaining.Second == 0)
        {
            DoSomething();
        }
        else
        {
            t.Remaining= t.Remaining.AddSeconds(-1);
            Label7.Text = t.Remaining.ToLongTimeString();
        }
    }

and my DoSomething() function:

     public void DoSomething()
        {

// Doing a lot of things....

            MultiView1.ActiveViewIndex = 3;
        }

The DoSomething function works correctly - I have a button that calls this function which also works. However, I want the function to be called when the remaining seconds reach 0 as well.

Answer №1

Indeed, I have experimented with this issue. Despite confirming that my C# function DoSomething() is functioning correctly after debugging, the View stubbornly refuses to update. Each time DoSomething() is called, the Timer starts ticking once more...

I stumbled upon a JavaScript function:

function stopTimer()
{
      var timer = $find("<%=Timer1.ClientID%>")
     timer._stopTimer();
}

Alas, the challenge lies in determining where to execute this function.

Update: It has come to my attention that my DoSomething() function is being invoked multiple times. When the Timer reads 0, the function executes every tick.

Another approach: A novice's solution :)

  1. Introduce a second Timer and set Timer2.Interval to an exceedingly high value like 9999999.
  2. In the Timer1_Tick event:

    t.Remaining = t.Remaining.AddSeconds(-1); Label7.Text = t.Remaining.ToLongTimeString();

            if (t.Remaining.Minute == 0 && t.Remaining.Second == 1) Timer2.Interval = 1000;
    
  3. Invoke the C# function during Timer2_Tick.

The rationale behind this workaround: You cannot directly call a C# function from the Tick event when the Timer serves as the trigger for an UpdatePanel.

**While I understand that there may be a more optimal solution involving JavaScript, my impending deadline leaves me no choice but to proceed with this method.

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

What is the process for setting up a command in Visual Studio 2010 that allows for easy toggling between an aspx code behind file and its corresponding markup or source view?

When working in Visual Studio 2010 and opening the code behind file of an aspx page, pressing F7 will take you to the WYSIWYG design view of the file. To access the actual markup or source view, you need to press Shift-F7. I am looking for a command in Vi ...

What is the process for obtaining JQuery from the getbootstrap website?

How can JQuery be included from the website 'getbootstrap.com'? This screenshot appears to display an older version of the site, possibly 4.6: https://getbootstrap.com/docs/4.6/getting-started/introduction/ What is the method to access JQuery f ...

Implementing PInvoke functionality specifically for the Windows Mobile platform

Trying to call a function from an unmanaged C++ dll has been my current challenge. void foo(char* in_file, char * out_file) In my C# application, I define the same function like this: [DllImport("dll.dll")] public static extern void foo(byte[] in_file, ...

Using Highmaps in a VueJs application involves passing a state to the mapOptions for customization

I'm currently struggling with passing a vuex state to mapOptions in vuejs components. Here is the code snippet: <template> <div> <highcharts :constructor-type="'mapChart'" :options="mapOptions" class="map">&l ...

Exploring the inner workings of unit testing

I am new to the world of unit testing and have never written any tests before. However, I am eager to incorporate them into my upcoming project. Below is an excerpt of my code: public class UnitOfWork : IDisposable, IUnitOfWork { private IDbContext co ...

A helpful guide on using workbox to effectively cache all URLs that follow the /page/id pattern, where id is a

Looking at this code snippet from my nodejs server: router.get('/page/:id', async function (req, res, next) { var id = req.params.id; if ( typeof req.params.id === "number"){id = parseInt(id);} res.render('page.ejs' , { vara:a , va ...

Revolutionary AJAX-powered File Upload feature

I am facing an issue with a dynamic file upload code where I need to upload multiple files using ajax. Despite trying the provided code, the request file count is showing as 0. I would appreciate any help in resolving this problem. <input id="Button ...

Storing a class method in a variable: A guide for JavaScript developers

I am currently working with a mysql connection object called db. db comes equipped with a useful method called query which can be used to execute sql statements For example: db.query('SELECT * FROM user',[], callback) To prevent having to type ...

Exploring the possibilities of maximizing, minimizing, resizing, and creating a responsive design in dialog boxes using jQuery UI JavaScript and

I'm trying to create a dialog with maximize, resize, and minimize buttons like those found in Windows OS. I want the dialog to be responsive and draggable as well. I've been using jQuery, jQuery UI, and extended dialog frameworks, but I haven&apo ...

Switch up the icon when the text is tapped

Hello everyone, I am fairly new to the world of coding and have been playing around with creating a hamburger-style menu for my website. So far, I have successfully made it so that when the user clicks on the hamburger icon, it changes into a close icon. H ...

Pass a variable to PHP using AJAX

I am currently facing an issue with sending an input value to PHP via AJAX. I am attempting to generate a datatable based on user input. Below is the code snippet: <input class="form-control" id="id1" type="text" name="id1"> My JavaScript code: & ...

Error in ASP.NET AJAX toolkit due to security breach

Recently, I encountered a problem with my ASP.NET WebForms application that utilizes the ASP.NET AJAX Toolkit. Everything was working smoothly on my old machine running Vista until its hard drive failed. After switching to a new Windows 7 Ultimate machine, ...

Retrieve information back onto the webpage following an AJAX request and serial port communication

Just getting started with JavaScript and Node.js I have set up a Raspberry Pi running Node.js, which is connected to an embedded device via a USB to UART connection. The USB is plugged into the Raspberry Pi, allowing me to send and receive data at a basic ...

Changing the background color of an answer box in React when the user clicks on it

I am currently developing a Quiz application that includes a question and four answer options. The goal is to modify the background color of the selected option when a user clicks on it. Essentially, when a user clicks on an answer, it should change color, ...

Calculate the total value of a specific field within an array of objects

When pulling data from a csv file and assigning it to an object array named SmartPostShipments [], calculating the total number of elements in the array using the .length property is straightforward. However, I also need to calculate the sum of each field ...

Is the memory efficiency of Object.keys().forEach() in JavaScript lower compared to a basic for...in loop?

Picture a scenario where you have an extremely large JS object filled with millions of key/value pairs, and your task is to loop through each of them. Check out this jsPerf example that demonstrates the different techniques for accomplishing this, highlig ...

What impact does nesting components have on performance and rendering capabilities?

Although this question may appear simple on the surface, it delves into a deeper understanding of the fundamentals of react. This scenario arose during a project discussion with some coworkers: Let's consider a straightforward situation (as illustrat ...

Determining the Validity of a Date String in JavaScript

I encountered an issue while attempting to validate a date string using the following code: const isValidDate = (date: any) => { return (new Date(date) !== "Invalid Date") && !isNaN(new Date(date)); } For instance: let dateStr = "some-random-s ...

Button functionality works smoothly on desktop but experiences issues with multiple submissions on mobile devices such as iPhones

Preventing multiple form submissions in asp.net webform functions correctly on a desktop version, but encounters issues on the mobile version of Safari or Chrome on iPhone. The following script prevents users from submitting the same form multiple times b ...

Tips for automatically scrolling a modal while reading a log file

I am seeking assistance with setting up a modal that automatically scrolls to the bottom when opened. The modal is updated with information from a logfile using XMLHTTP request. Below is the code snippet: <style> /* Customize the modal for logging ...