Invoke multiple JavaScript functions from C# upon clicking

After some research, I was able to successfully call a javascript function from c# in the code snippet below. However, I am encountering an issue where I can only use it once per c# method. Can someone please guide me on how to call more than one function in a method? My experience with C# is quite limited.

protected void btnAdd_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "firstEvent(event)", true);
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "secondEvent(event)", true);
}

Answer №1

I encountered a similar issue while working on a project with Blazor Webassembly. To resolve it, I made sure to await every call.

If the script manager does not allow direct awaiting, you can try:

protected async void btnAdd_Click(object sender, EventArgs e)
{
    await Task.Run(() => ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "firstEvent(event)", true));
    await Task.Run(() => ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "secondEvent(event)", true));
}

This issue might occur because the script manager cannot handle multiple calls simultaneously and may end up ignoring the second call. This was my experience with it, at least.

Answer №2

Alright, so here's the dilemma you're facing.

Just to clarify, when you use that command, it simply inserts some script into the webpage and sends it to the client side.

There are two ways to tackle this issue. You can combine both function calls into one, like so:

ScriptManager.RegisterStartupScript(This.Page, Page.GetType,
  "text", "test1();test2();", True)

Alternatively, you can do it like this:

ScriptManager.RegisterStartupScript(This.Page, Page.GetType, "text", "test1();", True)
ScriptManager.RegisterStartupScript(Me.Page, Me.GetType, "text2", "test2();", True)

Make sure to give a new "key" name - if you skip this step, the second one will overwrite the first one.

However, even doing this won't cut it:

    ScriptManager.RegisterStartupScript(this.Page, Page.GetType, "text", "test1()", True)
    ScriptManager.RegisterStartupScript(Me.Page, Me.GetType, "text2", "test2()", True)

Notice the missing ";" after the function.

So,

 Test1()   - only works for one
 Test1();  - will work if you add more

If you omit the trailing ";", then the script gets injected as:

Test1()Test2()

However, what you actually need is:

Test1();Test2();

Therefore, either include both calls in a single script inject like this:

Test1();Test2();

Or if you prefer using two separate script inject calls?

Ensure that you have unique key names for each, and also remember to add the trailing ";" so that they are recognized as distinct JavaScript function calls.

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

Generate JSON using JavaScript and post it to a web server by utilizing Ajax and PHP

I have researched extensively on the topic but I am still unable to make it work. I am trying to create an array in javascript and then utilize ajax to send it to a php file in order to generate a json file on the web server. This is my first time working ...

Is there a way to position the menu above the button?

I need some help with my menu. Currently, it is showing up below the button and within my footer instead of above the content like I want it to. If anyone can assist me in understanding what I am doing wrong, I would greatly appreciate it. Thank you for ta ...

Transitioning to ASP.NET Core 2.0: Compatibility issues arise with netcoreapp2.0 for certain packages

I'm encountering issues while updating to NET Core 2.0 as I'm seeing errors related to the packages installed with the reference. Possible cause of the problem: The output indicates a reference to netcoreapp1.0: The Microsoft.EntityFramework ...

What is the best way to create a Type for approved image formats?

I've been tasked by the client to create a list of supported icon names using TypeScript. However, as a newcomer to TypeScript, I'm finding it challenging to accomplish this. Here is my SVG component containing over 100 SVG icons. CustomIcons.t ...

I am currently working with a JavaScript file that receives input from an HTML page. My task is to incorporate this variable into a CSS style that is embedded within the JavaScript file

I recently started utilizing simplemaps and came across a JavaScript file that contains a function to extract values from an HTML page. Here's the JavaScript function: function getValue(intvalue){ alert(intvalue); var mapval = intvalue; } var simple ...

The issue arises when the .scroll event listener fails to accurately return true or false in

This code snippet determines whether an element is within the visible screen area. However, it seems to be returning an undefined value instead of true or false as intended. The function needs to output true or false for later use in higher-order operation ...

Problem Alert: Click Event Not Functioning on Generated Links

Take a look at these two code snippets. Despite other jQuery functions in the same JS file working fine on the UL element, nothing seems to be happening with these. Is there something obvious that I am missing? <ul id="activityPaganation" class="paga ...

Updating the properties of items in an array using React

Today, I was working on React and found myself stuck due to my limited JavaScript knowledge. I am trying to update the "name" property value of any object in this array. Check out the Codesandbox demo: https://codesandbox.io/s/dank-rain-udjcxe?file=/src/ ...

NodeJS: Use setInterval to continuously execute a loop as long as a specific variable remains true

function setNormal() { console.log(1) } function setAlert() { console.log(2) } function alertFunction() { alertVar = setInterval(alertFunc, 600); } function alertFunc() { setAlert() setTimeout(setNormal, 300) } alertFunction() }); I ...

Refreshing a template in Angular 2 (4) from the backend

I am currently incorporating backend-rendered templates into my Angular 4 application. However, I am facing an issue where the templates need to be reloaded after a user logs in. Can someone please provide assistance with this matter? I have attempted the ...

Find and extract items from a list by using a property value that is located within another list inside it

I have an order object with a partial class that tracks changes in its history: public class SomeOrder { public string OrderNumber { get; set; } public string Status { get; set; } public IEnumerable<SomeOrderChanges> ChangesHistory { get; ...

Tips for incorporating material-ui icons into the column component of a data-grid component

I am currently working with the material-ui data-grid and I would like to display Edit icons from material-ui next to each row. Unfortunately, the data-grid does not provide any props specifically for this purpose. Below is the code snippet: import React ...

Issue encountered while attempting to include a ScriptManager on the page

Currently using VS2010 and .Net 4, I am attempting to include a ScriptManager on my page in order to reference an AJAX Enabled WCF Service. However, upon adding the ScriptManager control and viewing the page, I encounter the following error. I am unsure ho ...

Manipulating text field value in Javascript and PHP

I'm currently working with a script that retrieves 2 values from my database. $(document).ready(function() { <? $link=new mysqli($serveur,$login,$pass,$base); mysqli_set_charset($link, "utf8"); $r=mysqli_query($link, "select sujet ...

Retrieving Object from UnmanagedMemoryStream in ResourceDictionary of an External Assembly

In the following code, I am working with an UnmanagedMemoryStream. How can I deserialize it to get the object? Specifically, I am trying to retrieve a Resource (rd.xaml) from an Assembly: string address = @"WpfControlLibrary1.dll"; Assembly skinAssembly = ...

Using JQuery to make POST requests is successful, however, utilizing the XMLHttpRequest object to make

Currently, I am attempting to make a POST request from Javascript to my server in PHP but without utilizing jQuery. The following code successfully sends the required data to the database: var msg = {}; msg['name'] = 'joe'; msg['m ...

Using Typescript to create an asynchronous function without explicitly declaring a Promise

When you examine TypeScript's async function, you may notice the redundancy with "async" and "Promise<type>". public async test(): Promise<string> { return "Test"; } Is there a way to configure TypeScript to handle async types ...

Concerns arise with jQuery grid compatibility in Firefox browsers

I have found an interesting tutorial on draggable image boxes grid at this link. Although everything is functioning properly, I am encountering an issue with the drag function specifically on the home page when using Firefox. As a beginner in jQuery, I am ...

Exploring the wonders of Angularjs and the dynamic capabilities of streaming data

Using AngularJS's $http to request streaming data like this: $http({ method: 'POST', url: url, data: JSON.stringify(data), headers: config }).success(function(responseData) { console.log(responseData); }).error(funct ...

Tips for creating a mirrored iframe without the need to load the URL twice: CSS does not trigger the desired effect

I have a unique requirement for two iframes - I want only the first iframe to load a specific URL. Once the first iframe finishes loading, I need the second iframe to display the same content without actually loading the URL again. Here is the approach I h ...