Executing RegisterStartupScript repeatedly in C#

Greetings to all,

Here is a snippet from my code:

start code
protected void Button1_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "temp", "<script>loadAdditionalInfoDialog(info1)</script>",false);

ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "temp2", "<script>loadAdditionalInfoDialog(info2)</script>",false);
}
end of code

The loadAdditionalInfoDialog() function triggers a small window where users can input information and click "OK" to move to the next step.

However, when I click on Button1, I only see the second RegisterStartupScript in action, meaning loadAdditionalInfoDialog(info2) works but I can't enter info for the first one, loadAdditionalInfoDialog(info1).

I am seeking a solution where I can input info for loadAdditionalInfoDialog(info1) first upon clicking Button1, followed by entering info for loadAdditionalInfoDialog(info2).

Many thanks for any help.

Button1_Click is primarily for testing purposes. In reality, I will trigger loadAdditionalInfoDialog() when receiving data in a Repeater:

protected void btnRedeemAll_Click(object sender, EventArgs e)
    {
        foreach( RepeaterItem itm in repGiftResults.Items )
        {
            /*
            code to gather parameters
            */
            if (pr.AdditionalFieldsEnabled == true)
                    {
                        ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "temp", "<script>loadAdditionalInfoDialog(1," + pr.ID + "," + giftId + ",'" + txtQty.ClientID + "'," + tokenId + ")</script>", false);
                        
                    }
        }
    }

Thus, calling loadAdditonalInfoDialog() a second time upon clicking "OK" is complicated due to the need for numerous parameters in the repeater.

Answer №1

It seems like your code should be working fine, but make sure your info1 and info2 are defined and double-check the logic in loadAdditionalInfoDialog function. For testing purposes, consider adding an alert in it. It might be beneficial to consolidate both calls into a single block for efficiency.

Update: Based on your comments, this is what I understand you are trying to achieve:

Add a hidden field inside your repeater template:

 <asp:HiddenField ID="hdf" runat="server" />

In your code-behind, you can try the following approach:

        foreach (RepeaterItem item in cdcatalog.Items)
        {
            // Place your condition here (e.g., if (pr.AdditionalFieldsEnabled == true)
            if (item.ItemIndex == 1)
            {
                // Access the hidden field to store your parameters for the next call (multiple parameters can be added and read using JS)
                HiddenField hdf = item.FindControl("hdf") as HiddenField;
                hdf.Value = "info2";
                // Pass the client ID for the hidden field to access it in loadAdditionalInfoDialog and retrieve the parameter
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), String.Format("temp_{0}",item.ItemIndex),
                                                   String.Format("<script>loadAdditionalInfoDialog('info1',{0});</script>",hdf.ClientID),
                                                    false);
            }
        }

Your script can handle the process as follows:

 <script type="text/javascript">
        function loadAdditionalInfoDialog(param, hdfId) {
            // Handle actions here
            var info = prompt("Please enter ", param);

            if (info != null) {
                // Perform desired actions with the collected info

                // This part should be in your "ok" button click event to determine if you need to call the second window.
                if (info !== undefined) {
                    loadAdditionalInfoDialog(hdfId.value);
                }
            }


        }

    </script>

I hope this explanation proves useful for you.

Answer №2

If you are still searching for a solution, here is what I found effective in my own experience, tailored to your specific situation:

protected void Button1_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "temp", "<script>combineProcesses(info1, info2); </script>", false);
}

I have streamlined the two processes into one for efficient execution, but if a sequential approach is necessary, this method can still be beneficial.

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

Basic Search tool, displaying a <div>

Hey there, I've been searching for a solution for a while now and haven't found one yet. So here's my question: I created a simple website to display random recipes for those times when you're not sure what to make for dinner. I also w ...

What is the best way to search for items using only a portion of a phone number or typing a name in any case (uppercase, lowercase) and still get accurate results?

let contacts = [ { name: 'John', phone: 987654 }, { name: 'Sara', phone: 654321 } ] I am developing a contact manager app with various functions to manage contacts. Add new contac ...

How can I effectively organize an Angular2 component library for optimal efficiency?

Looking to develop an Angular2 datepicker component with the intention of releasing it and using it in multiple projects. Wondering about the best way to structure the project for this specific purpose compared to a typical Angular2 project created with an ...

Developing with node and express: optimizing your workflow

After researching various blogs and tutorials on node + express development workflow, there is one crucial aspect that seems to be missing: When developing, which version of the app should you have open in your browser? The source app, featuring clean, ...

Add attributes to the top level

<li class="page_item"><a href="javascript:">A</a> <ul class="children"> <li class="page_item"><a href="">1</a></li> <li class="page_item"><a href="">2</a></li> </ul> < ...

Set JSON Value Session

In the table, there is an option to edit certain entries using a button. I have developed a function that retrieves JSON data and populates the table with it. This process happens before any other actions. Once the data is loaded, my goal is to create a c ...

Using Context to Populate a DataSet with Entity Framework 4

How can I extract data from a Context and use it to populate my DataSet in order to display it in a TreeView Control? I have retrieved the Data using spCmsCategoriesReadHierarchy function. My goal is to effectively transfer this Data into a DataSet for fu ...

Is there a way to repurpose a function to work with both ids and classes?

My current code is affecting all elements instead of just the intended one. I've experimented with classes and ids, ruling out those as potential issues. I'm hoping for my JavaScript to target only the selected element, not all of them. Check ou ...

Tips for recognizing the click, such as determining which specific button was pressed

Currently, I am utilizing Angular 6. On the customer list page, there are three buttons - "NEW", "EDIT", and "VIEW" - all of which render to one component. As a result, it is crucial for me to determine which specific button has been clicked in order to ...

Trouble with event.preventDefault functionality

This snippet of code I'm working on is pretty basic, nothing too intricate. $("input#send").submit(function(event){ event.preventDefault(); $.ajax({ type: 'POST', url: add.php, data: data, succe ...

Utilizing JQuery's $(document).ready() function following a window.location change

I'm having trouble getting a JavaScript function to run after being redirected to a specific page like "example.com" when the DOM is ready for it to work with. Unfortunately, it seems that $(document).ready() is running before "example.com" finishes l ...

Utilizing JavaScript to implement conditional if-else statements on CSS properties

I am trying to implement conditions on CSS properties in JavaScript. What is the most efficient approach to achieve this? <html> <head> <title>TOOLTIP USING JAVASCRIPT</title> <style> span{ curso ...

The functionality of JQuery ceases to function properly once the BxSlider plugin is activated

I've encountered a strange issue while using the BxSlider plugin of jQuery on my page. When I implement the code for the slider with BxSlider, all other custom functions seem to stop working without any errors being displayed in the console. I've ...

Issue encountered while rendering tables with Jquery-dataTables

Encountering an issue with jquery datatables when fetching data from a URL using ajax calls. Implementing the codeigniter framework, I utilize the datatables library to create datatable objects by invoking the echo $this->datatables->generate() metho ...

Expiration Alert: SSL Certificates for HERE Links will expire shortly

Our SSL certificates for the following URL's are approaching expiration: *.base.maps.ls.hereapi.com geocoder.ls.hereapi.com Do you have any information on when these URLs will be updated with new certificates? ...

Error message: Encountered JavaScript heap out-of-memory error during Azure DevOps React Container Production Build

I am facing challenges in building a React production Docker container with Azure DevOps pipelines. Despite upgrading my build environment and code, the pipeline failed to run successfully. After conducting some research, I attempted to add the "--node-fla ...

Extending a Sub-Object in JavaScript

I'm attempting to include new attributes to the sub-object within object1. However, I am facing issues with it being overwritten. const object1 = { a: 1, b: 2, c: 3, sub: { e: 1, f: 2 } }; const object2 = Object.assign({ j: 4, ...

Having trouble getting the HTML input textbox onChange event to fire properly?

This is the code I have been working on: <script language="JavaScript"> function toggle() { if (this.value=='1') { document.getElementById('dbOn').style.visibility='visible'; } el ...

OpenIdDict seems to have an issue where the account selection window for Google and Facebook logins is not appearing

I am currently utilizing OpenIdDict for user authentication. I successfully set up Google and Facebook logins based on the provided example here. However, I have encountered an issue where the account selection window does not appear if the user has previo ...

npm encountered an error while trying to install selenium-webdriver using the npm install command

My operating system is Windows Server 2008 R2 EE and I have the npm package manager installed. I am attempting to install the Selenium Webdriver package using the command below. Command: npm install selenium-webdriver However, when running this comma ...