The ScriptManager.RegisterStartupScript function does not execute a second time when used inside an UpdatePanel

My aspx page

<span>
 <asp:UpdatePanel ID="upPlayBtn" runat="server" >
  <ContentTemplate>
   <asp:Button runat="server" id="btn" Text="Play" OnClick="btnPlay" />
  </ContentTemplate>
 </asp:UpdatePanel> 
</span>

<script type="text/javascript">

 function LoadPlayerWindow() {
     LoadPlayWindow("<%=PlayLink%>");
 }
 function DisplayErrorMessage() {
     alert("An error has occurred. Please try again later.");
 }

</script>

My CS page

protected void btnPlay(object sender, EventArgs e)
{
if(condition)
   ScriptManager.RegisterStartupScript(upPlayBtn, upPlayBtn.GetType(),"tabs", "LoadPlayerWindow();", true);
  }
 else
  {
   ScriptManager.RegisterStartupScript(upPlayBtn, upPlayBtn.GetType(), "tabs", "DisplayErrorMessage();", true);
  }
}

Upon clicking the "Play" button for the first time, either LoadPlayerWindow() or DisplayErrorMessage() is executed based on the condition. However, if the button is clicked again, only "btnPlay" function is triggered without any JS function.

If the page is refreshed, the functionality works correctly once more.

Answer №1

<span>
<asp:UpdatePanel ID="upPlayBtn" runat="server" >
<ContentTemplate>
  <asp:Button runat="server" id="btn" Text="Press Play" OnClick="btnPlay" />

   <script type="text/javascript">
    function LaunchPlayer() {
     OpenPlayWindow("<%=PlayLink%>");
    }
    function DisplayErrorPopup() {
     alert("There is an issue. Please try again later. Thank you!")
    }
   </script>

</ContentTemplate>
</asp:UpdatePanel> 
</span>

Answer №2

I apologize for not being able to provide the code in the comments section, so I'm sharing it here as an answer. Below is the code snippet that you can use. Kindly paste it into a new project and test its functionality.

If there are any mistakes in how I've replicated the issue (incorrect code), please feel free to leave a comment for clarification.

If the code works fine in a separate project but not in your current setup, the issue may lie within other parts of your code that are not visible in your question.

aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="Practice_Web.WebForm2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server">
    </asp:ScriptManager>
    <div>
        <span>
            <asp:UpdatePanel ID="upPlayBtn" runat="server">
                <ContentTemplate>
                    <asp:Button runat="server" ID="btn" Text="Play" OnClick="btnPlay" />
                </ContentTemplate>
            </asp:UpdatePanel>
        </span>
        <%--It functions properly even if the script is placed here--%>
    </div>
    </form>
</body>
<script type="text/javascript">

    function OpenPlayerWindow() {
        alert("Thanks!");
    }
    function OpenPlayerWindowForError() {
        alert("Please check back later. Thanks!");
    }
</script>
</html>

aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Practice_Web
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //This is just a simulation of the conditional part of the original code
            if (Session["condition"] == null)
                Session["condition"] = false;
            else
                Session["condition"] = !Convert.ToBoolean(Session["condition"]);
        }

        protected void btnPlay(object sender, EventArgs e)
        {
            bool condition = Convert.ToBoolean(Session["condition"]);
            if (condition)
            {
                ScriptManager.RegisterStartupScript(upPlayBtn, upPlayBtn.GetType(), "tabs", "OpenPlayerWindow();", true);
            }
            else
            {
                ScriptManager.RegisterStartupScript(upPlayBtn, upPlayBtn.GetType(), "tabs", "OpenPlayerWindowForError();", true);
            }
        }
    }
}

Answer №3

Take a look at the code snippet below:

protected void btnPlay(object sender, EventArgs e)
{
    if(condition)
       ScriptManager.RegisterStartupScript(this, GetType(),"tabs", "OpenPlayerWindow();", true);
    }
    else
    {
        ScriptManager.RegisterStartupScript(this, GetType(), "tabs", "OpenPlayerWindowForError();", true);
    }
}

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

Is there a way to switch on and off an ngrx action?

Here is a statement that triggers a load action to the store. The relevant effect will process the request and return the response items. However, my goal is to be able to control this action with a button. When I click on start, it should initiate dispa ...

What is the Typescript definition of a module that acts as a function and includes namespaces?

I'm currently working on creating a *.d.ts file for the react-grid-layout library. The library's index.js file reveals that it exports a function - ReactGridLayout, which is a subclass of React.Component: // react-grid-layout/index.js module.exp ...

Remove the attribute from the element in the ng-repeat loop

Here is my ng-repeat code snippet: <th ng-repeat="field in tableFields" translate="{{field.headerTitle | translate}}" ts-criteria="{{field.sortable ? field.fieldKey : null}}"> <label class="i-checks" ng-if="field.isCheckbox"> & ...

Issue with highcharts and vue.js: creating a unique chart for displaying measurements

Currently, I am integrating Highcharts and Vue.js simultaneously while incorporating multiple charts on my webpage. As of now, I have successfully displayed data on all the charts without encountering any issues. However, my goal is to assign a special tit ...

Running a script through the terminal using an electron js application, but the process necessitates the installation of node js

I am currently working on a project that involves running a script through the system terminal using my Electron.js application. However, I am facing an issue with new users who may not be technically proficient and do not have Node.js installed on their s ...

organize the values based on their priority using reactjs

I'm facing a challenge involving two arrays of objects: array1 and array2. I need to display only three values from both arrays, with priority given to array1. The requirements are as follows: if array1 contains 3 elements, all three should be shown. ...

"Utilizing FabricJs with Multiple Canvases to Display the Same Image Repeatedly

Within a loop ranging from 1 to 2, I have created two canvases on the screen and stored them in an object. However, when I load the same two images onto each canvas, only the last canvas displays the images. Why is it not loading on both canvases? Interest ...

"Is it possible to move the text on the canvas by dragging it to where you want it to be

Seeking help again after an unsuccessful attempt. How can I allow the user to add text to the canvas by dragging it to their desired location? For example, if they input text somewhere, it should appear on the canvas and then be draggable to any position ...

The FormData function is unable to retrieve the input fields of a form

My Unique Code <!DOCTYPE html> <html> <body> <div id="custom-form-sample"> <form enctype="multipart/form-data"> <input type="text" name="custom-text" /> <input type="radio" name="custom-radio" ...

Decoding deeply nested JSON data using JavaScript

After browsing through countless threads on the topic, I have yet to find a solution. I successfully parsed a JSON response that looks like this: { "1": { "id": "1", "name": "Fruit", . . . "entities": { ...

How to Display Bootstrap4 Modal in VueJS without using Jquery

Is there a way to display a Bootstrap modal from a function in VueJS using vanilla JS? I am working on a project that only uses standard Bootstrap 4 and not BootstrapVue. //component.vue <template> <div> <button type="button" class ...

Using Vue.js to conditionally render data in a v-for loop

Below is the code snippet I am working with: <article class="project-card" v-for="item in en.projects" Additionally, here are some import statements: import fr from '../assets/datas/fr.json' import en from '../assets/datas/en. ...

Checking the conditional styling implemented with Material UI makeStyles: a step-by-step guide

For the past few weeks, I've been working on a React app where I heavily rely on Material UI components. One particular component changes its style based on the values of its props. To achieve this, I used the following approach: const useStyles = ...

Unable to retrieve selected value with AJAX

My select box is set up with some values, and I'm using AJAX to send data to PHP and display that data inside a <div>. However, my code doesn't seem to be working properly. Interestingly, when I used a button to get the value from the sele ...

Searching for various object values within an array and then adding two properties together in JavaScript

I am working with an array of objects that require me to analyze two properties in order to calculate a value. let data = [ { NodeId: "9837f279", NodeName: "Node1", summary: { current: 50, limit: 75 ...

Using Svelte to effectively connect to a specified object within an array

Check out this code snippet: <script> let data = [ {id: 1, first: "x"}, {id: 2, second: "y"} ]; </script> <input type="text" bind:value={data.first}/> If you modify the value in the input field and ...

Using AngularJS to bind to the 'src' property of an <img> tag

There is a table on my website with numerous rows, and each row contains a preview image that should appear in the top right corner when the mouse hovers over it. I attempted to insert an image tag with AngularJS binding for the URL in the src attribute l ...

Extracting and retrieving the value from the paramMap in Angular/JavaScript

How can we extract only the value from the router param map? Currently, the output is: authkey:af408c30-d212-4efe-933d-54606709fa32 I am interested in obtaining just the random "af408c30-d212-4efe-933d-54606709fa32" without the key "authke ...

Activate continuous speech identification

Is it possible to activate the capability of recognizing continuous speech through the REST API (using javascript SDK) with the Bing Speech API? The Javascript SDK example available at https://github.com/Microsoft/Cognitive-Speech-STT-JavaScript only seem ...

What is the solution for - Uncaught TypeError: Cannot access the property 'scrollHeight' of an undefined element?

Could someone kindly assist me in resolving an issue? I recently encountered a problem with a script I have been using on the Chrome console. This script has been working perfectly fine for the past few days. However, today when I ran it, I started receiv ...