Unable to modify JavaScript variable that was initialized within an UpdatePanel

I've been struggling with this issue for days.

1- A user clicks on one of the buttons.
2- The button click inserts a .js variable into LABEL->lbJavaScriptVar
3- Sys.Application.add_load(GridJson); invokes the .js function

The issue is, I am unable to modify the value of the variable "SHOWTHIS" inside an UpdatePanel as the value never changes.

-----------------------------[aspx]------------------------------------

<head>
<script type="text/javascript">
    function GridJson()
    {
        alert(SHOWTHIS);
        document.getElementById("Grid").innerHTML = 
                "<tr><td>" + SHOWTHIS+ "</td></tr>"
    }            
</script>
</head>

...

<asp:UpdatePanel runat="server">
<ContentTemplate>

<asp:Button ID="btMan" runat="server" OnClick="btMan_click" Text="Man"/>
<asp:Button ID="btWoman" runat="server" OnClick="btWoman_click" Text="Woman"/>

<asp:Label ID="lbJavaScriptVar" runat="server" ></asp:Label>

<table id="Grid" border="5" class="cssMiniGrid"></table>
<script type="text/javascript">Sys.Application.add_load(GridJson);</script>

</ContentTemplate>
</asp:UpdatePanel>

-----------------------------[/aspx]------------------------------------

-----------------------------[.cs]------------------------------------

(btMan_click)...
lbJavaScriptVar.Text = "<script> var SHOWTHIS= 9999</script> ";

(btWoman_click)...
lbJavaScriptVar.Text = "<script> var SHOWTHIS = 7777</script> ";

-----------------------------[/.cs]------------------------------------

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

EDITED...I managed to resolve it thanks to your suggestions, make these changes to ensure it works

.ASPX<
[ALTER]function GridJson() ------> function GridJson(SHOWTHIS) {

.CS
[DELETE](btMan_click)... 
[DELETE]lbJavaScriptVar.Text = "<script> var SHOWTHIS= 9999</script> ";   
[DELETE](btWoman_click)... 
[DELETE]lbJavaScriptVar.Text = "<script> var SHOWTHIS = 7777</script> "; 
[INCLUDE]ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "GridJson(" + "THANKS" + ");", true);

Note: Initially, I wrote this code within a web user control, but now it's placed under the root page

Answer №1

Here's a simple way to achieve this:

Add the following code in your C# file:
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "myFunction('value');", true);

Then add this JavaScript function:

function myFunction(parameter){
   SHOWTHIS= parameter;
}

For more information, please visit this link.

Answer №2

Insert script into HTML using ScriptManager.RegisterStartupScript

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

Executing a function after a subscriber has finished in Angular 8+

Welcome fellow learners! Currently, I am diving into the world of Angular and Firebase. I am facing an interesting challenge where I fetch ticket data from my collection and need to add new properties to it. However, the issue arises when my ordering funct ...

How can you leverage the power of useState in a custom React hook?

Here is a code snippet for a custom hook I created: const useShowBg = () => { const [showBg, useShowBg] = useState(false); return [showBg, useShowBg]; }; export default useShowBg; In my component, I import and use the custom hook like this: im ...

"Previewing multiple images before uploading for a better visual experience

I am working on a project to enable previewing multiple images, but I encountered an issue. My current code only works when uploading 2 images. I want the preview to work for as many images as the user uploads. Here is the relevant JavaScript code: var a ...

Step-by-step guide to aligning layout using material design in generator-gulp-angular

I am currently using generator-gulp-angular with angular-material-design and ui-router All views are loaded into index.html in the <div ui-view></div> element However, when I attempt to center the element with material design directives insid ...

Having trouble activating the Samsung Tizen TV through the designated APIs

I currently have a Tizen Application for managing TV Operations such as Volume Controls and Power On/Off. I have implemented the use of b2bapis for Power Off functionalities, but I am struggling to locate comprehensive documentation on the same. The code s ...

What happens when Long AJAX requests run in SetInterval and exceed the specified interval time?

Imagine you have this line of code: setInterval(ajaxFunction,3000); The ajaxFunction in the code is a function that calls a PHP script and retrieves data. What if the request takes longer than 3 seconds? Will it stop the current request and begin again, ...

Manipulate the rows in a table by adding and removing using server side control through the power of Jquery

I need to dynamically remove a row from my table based on a condition and later re-add it. This way, the HTML content will not be accessible by screen-readers when hidden. However, the code I have tried so far is not working as expected. Here is the snipp ...

The autocomplete feature in my jquery textbox is malfunctioning

Hey everyone, I'm fairly new to jquery and currently in the process of learning it. I'm attempting to create an autocomplete textbox feature using jquery. However, I seem to be encountering an error that I'm not able to identify. Whenever I ...

Why does Axios default to sending my POST request with Content-Type application/x-www-form-urlencoded when passing a string as the request body?

While working with axios to make POST requests, I encountered an interesting behavior. I am passing URLs entered by the user to my Spring RestController, which accepts the request body as a String. The code snippet looks like this: @PostMapping("user/ ...

Are elements such as String and Number to be classified as "constructor functions" within JavaScript programming?

After spending a few weeks poring over tutorials, I've finally uncovered an interesting fact. When using the prototype property on a constructor function, the key/value pairs on that prototype property are actually copied to the proto property of the ...

Executing a NestJs cron job at precise intervals three times each day: a guide

I am developing a notifications trigger method that needs to run three times per day at specific times. Although I have reviewed the documentation, I am struggling to understand the regex code and how to customize it according to my requirements! Current ...

SSR with Material UI Drawer encounters issue during webpack production build meltdown

When I attempted to utilize the Material UI SSR example provided by Material-UI (Link), it worked successfully. However, my next step was to integrate the Material-UI Drawer into this example. To do so, I utilized the Persistent drawer example code also pr ...

Guide on implementing a text display switch using CSS

I am working on two radio type menus to allow users to select different payment methods which will reveal corresponding information. However, I am facing a challenge in implementing the Precautions content below. Can someone guide me on how to achieve this ...

Issue arise when utilizing async/await in conjunction with .forEach method

My code is attempting to make a basic request to Redis in order to retrieve all the values (not keys) from my database. However, I am encountering an issue where the tab is being returned before the .forEach function even begins. This is evident because ...

Unable to retrieve successful response data/status from my Node/Express server to the client application (React): "ReferenceError: response is not defined"

I have set up a simple Node/Express server and created a route to handle form data submission from React. The post request is utilizing async/await with the Fetch API. I'm unsure whether the issue lies with my server-side route or how I've implem ...

Are we altering the scope or is there another factor at play?

My knowledge of JavaScript is quite limited, so I'm unsure about what mistake I might be making. Here's an example that works perfectly: myarray = []; myarray.push(1); This following example also works flawlessly: myarray = []; function exa ...

Develop a Playwright test script that includes fetch requests

My goal is to create an end-to-end test using Playwright for a website built with React. The website functions as follows: Upon initial rendering, it fetches a random fact from one API and then uses the first three words of that fact to fetch a random p ...

Error loading QR code column in HTML table on tablet device

I am working on a pharmacy application that displays a HTML table with QRcodes as one of its column values. I am using the QRcode.min js library to convert the string to QRcode. json = $.parseJSON(JSON.stringify(res.d)); // console.log('data ' ...

JSON geometry imported is not following the movement of the bones

After importing a model into my Three.js scene, I encountered an issue where the bones can be moved and rotated successfully, but the model's geometry does not follow these bone movements. For importing the JSON file and adding it to the scene, here ...

Transforming Json data into a pair of potential objects

I find myself in a scenario where I am receiving two different types of objects in Json format and faced with the task of deserializing them into their corresponding object types. The challenge lies in the fact that both types of objects are sent through t ...