Invoke a C# function from a button's onclick event using JavaScript

How can I implement something similar to this:

<script>
 google.maps.event.addListener(marker, "click", function (e) {
     var infoWindow = new google.maps.InfoWindow({
content: 
'<div><input type="text" id="txt_newpl" value="place name"/>' +
'</br> <input type="button" id="btn_newpl" value="submit" onclick="btn_newpl_Click" /></div>'
         });</script>

The C# code for this functionality would look like:

    protected void btn_newpl_Click(object sender, EventArgs e)
{...}

What is the best way to trigger this C# function from a JavaScript click event?

Answer №1

In order to activate a button event, you need to insert the following line of code in your javascript.

document.getElementById("btn_newpl").click();

Your button should include attributes runat="server" and OnServerClick="btn_newpl_Click".

If you encounter an issue where the input element is within a javascript string, you can retrieve the string value of the input and concatenate it with your string on the client side.

<input type="button" id="btn_newpl" value="submit" 
       OnServerClick="btn_newpl_Click"
       runat="server" />

<script>
var tmp = document.createElement("div");
tmp.appendChild(document.getElementById('btn_newpl'));

google.maps.event.addListener(marker, "click", function (e) {
    var infoWindow = new google.maps.InfoWindow({
       content: 
       '<div><input type="text" id="txt_newpl" value="place name"/>' +
       '</br>'+tmp.innerHTML+'</div>'
    })
});
</script>

Please be aware that you are not directly calling a C# function, but simply triggering the click event on web forms which results in a postback to the server. The server will detect the triggered event and execute the corresponding C# function.

Source: How to call a code behinds button click event using javascript

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

How can I position images in the center evenly?

I am currently working on implementing a 3D image carousel. It seems to work fine with an odd number of images, but when I add an even number of images and the positions change, the alignment gets offset to the left instead of center. Here is the link to ...

Discover the secret to automatically calling a function every minute when the page is loaded!

Our team is currently developing a PhoneGap application with 4 pages. We are in need of posting the current latitude and longitude every minute to our server. Fortunately, we are familiar with how to post values to the server as well as how to retrieve the ...

Is it possible to integrate Express 4 standalone middleware into an Express 3 application?

While I am not yet prepared to upgrade my Express 3 installation to Express 4, I am interested in utilizing some of the enhanced components in Express 4, such as express-session and compression. I have experimented with implementing these upgrades and eve ...

Issue: Angular 14 - Validators Not Resetting in Nested FormGroup

I am currently working on implementing a nested FormGroup. However, I have encountered an error when attempting to reset the form. Here is the structure of the form: form: UntypedFormGroup; this.form = this.fb.nonNullable.group({ f1: [''], f2: ...

Validation of time input in Angular7 using reactive forms with Material design

Dealing with an angular 7 reactive form, the input field in this form allows users to view and modify time. The issue arises when users enter nonsensical numbers in this field that do not align with valid time ranges (e.g., hours should be between 1-24, mi ...

Attempting to update the appearance of each item within an array by utilizing the ForEach() method

I am working on a function that dynamically creates new divs based on a specific condition. Once these divs are created, I store them in an array using the .push() method like so: function SnakeBody(){ BodySnake = document.createElement("div"); tabulei ...

Passing data back from an asynchronous function to its parent function in Node.js

Exploring the world of asynchronous programming is a new adventure for me as I delve into implementing Twilio video calls through Node.js. I've been grappling with calling a server-side function that in turn invokes another asynchronous function retu ...

Having Difficulty Formatting HTML Input in Next.js

I'm encountering difficulties when trying to style HTML form elements in Next.js. I've been unsuccessful in applying CSS using a simple class name from the imported stylesheet, but have managed to achieve some success with inline styling by using ...

Changing the language of the bootstrap datetimepicker (not just the datepicker)

tag, I am utilizing the most recent version of Bootstrap (4.2.1) in conjunction with the latest version of jQuery. Moreover, I have also integrated moment.js and jquery.datetimepicker into my project. Despite adding a locale file for language support, I ...

What is the proper way to attach an 'onChange' event listener to an input element using React?

When working with React, it's important to note that the onChange event in the code snippet below is considered an on input event handler, rather than an on change event handler: <input onChange={() => ()}></input> However, if your goa ...

Exploring the concept of global objects within the expressjs framework

Currently, I am working on building a school management system. One issue I encountered is related to the creation of global objects in my backend when a teacher sends a post request. I am wondering whether multiple teachers accessing the server will res ...

There is no component factory available for the DialogDataExampleDialog. Have you ensured to include it in the @NgModule entryComponents?

Currently, I am a beginner in Angular. I recently started integrating MatDialog into my project. To do this, I followed the code provided on the official Angular documentation page https://material.angular.io/components/dialog/overview. However, upon click ...

Leveraging the power of the max query function in mongoose

Just starting out with mongoose and navigating the world of correct queries can be a bit daunting for me. I have two straightforward Models: User: const UserSchema = new Schema({ name: String, age: Number, movies:[{ type: Schema.Types.ObjectId, ...

Adjust the vertical size and smoothly lower a text input field

When a user clicks on a textarea, I want it to smoothly change height to 60px and slide down in one fluid animation. Check out the JSFiddle example here: http://jsfiddle.net/MgcDU/6399/ HTML: <div class="container"> <div class="well"> ...

A guide on selectively removing a value from a javascript object when calling setState in ReactJS

updateDishDetails(id, quantity) { if (quantity !== 0) { this.setState( prevState => ({ bookingFormData: { ...prevState.bookingFormData, dishDetails: { ...prevState.bookingFormData.dishDe ...

Guide on Resolving AJAX Filtered Product List Issue with Missing Images in Django Ecommerce Website

I'm facing an issue while implementing filter functionality in my e-commerce project. When I utilized AJAX to generate a filtered product list, all the products are visible but the images aren't showing up. urls.py: urlpatterns = [ path(&apo ...

When ng-blur event is triggered, the model associated with the input field is updated; however, the input field regains focus simultaneously

Currently facing an issue with angular updating the focus of my interface after a bound variable change. There's an array of author objects being utilized, and I'm employing an ngRepeat to exhibit their names in inputs. Upon blur of the input, an ...

React-router version 6 now supports breadcrumbs and partially matching routes

Currently, I am utilizing react-router-dom v6.8.1 (the most recent version at the moment) and had previously implemented a breadcrumb system that was functioning well with a third-party library called use-react-router-breadcrumbs. However, as per their doc ...

Unable to assign multiple values to a bootstrap select from an array

Currently, I am dealing with a string: 93, 94 which represents the references of the values in a select option. My attempt to assign these values using: let values = "93, 94"; $('#property-categories').selectpicker('val', values); ha ...

What is the best way to retrieve a JavaScript session attribute within a JSP page?

function saveToSession() { var name = document.getElementById('name').value; var mobile = document.getElementById('number').value; sessionStorage.setItem("name", name); sessionStorage.setItem("mobile", mobile); docu ...