Issues with passing OnClientClick to the server-side OnClick method in my ASP.NET web application when returning true

I have tried multiple solution suggestions for this issue, but none seem to be working as intended. My goal is to trigger a JavaScript validation function before running the C# code behind method when the validation returns true. The OnClick should follow the operation of the javascript OnClientClick.

Some of the solutions I attempted can be found in these threads:

Executing OnClick code behind method after returning true from OnClientClick javascript function

Executing OnClick code behind method after returning true from OnClientClick javascript function

This is my current setup:

<asp:Button ID="btnAdd" runat="server" AutoPostBack="true" OnClick="btnAdd_Click" OnClientClick="btnAdd_Click(this, event);" Text="Add" UseSubmitBehavior="false"/>&nbsp;

function btnAdd_Click(sender, args) {
    if(confirm('Do you want to do a server trip?'))
    {
        return true;
    }
    else
    {
        return false;
    }
}

I also attempted:

<asp:Button ID="btnAdd" runat="server" AutoPostBack="true" OnClick="btnAdd_Click" OnClientClick="if (!Confirm()) return false;" Text="Add" UseSubmitBehavior="false"/>&nbsp;

function Confirm() {
    return confirm("Are you sure?");
}

Currently, I am experiencing an issue where the JavaScript always fires regardless of the outcome. Upon debugging, it shows that the JavaScript is indeed returning true to my solution, so the OnClick should be triggered. However, the break point in my click event on the code behind is never reached. Is there a site setting or some other factor preventing this from happening?

Any help would be greatly appreciated. Thank you in advance.

Answer №1

Here's a suggestion - you can achieve the same result without using that JavaScript function.

<asp:Button ID="btnAdd" runat="server" OnClientClick="return window.confirm('Are you certain?');" Text="Add" OnClick="btnAdd_Clicked"/>

protected void btnAdd_Clicked(object sender, EventArgs eventArgs)
{
    string test = "12345";
}

By debugging the btnAdd_Clicked method, you'll notice it executes the very first line of code.

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

The readline interface in Node that echoes each character multiple times

After creating a node readline interface for my project, I encountered an unusual issue. this.io = readline.createInterface({ input: process.stdin, output: process.stdout, completer:(line:string) => { //adapted from Node docs ...

Undefined return on Collection.get function in backbone.js

I'm encountering an issue with collection.get and model.get methods returning undefined values. Here is my initialization code: initialize: function () { this.collection = new productsCollection(); this.model = new productModel(); } And her ...

Is it possible to configure a DataContractSerializer to overlook errors in a file instead of crashing altogether?

Currently, I am utilizing DataContractSerializer to store various classes that form tree structures into XML files. Since the software is in its early development stages and the components are frequently changing, updating a class often results in the prog ...

Picture route leading to text box

I am currently working on a project and I need to save the image path from the Content/assets folder in my database. Right now, I am saving the path by entering it into a textbox and then passing it to my create method. How can I create a photo picker to ...

There is no $key present within an AngularFireDatabase.object

I have encountered an issue in my Angular application while attempting to update records on a Firebase database. I am utilizing AngularFireDatabase to bind the list initially, which is then intended to be used for updating specific records. However, the ch ...

Grid layout showcasing masonry gallery

I've spent some time looking for a Masonry gallery with a grid layout, but couldn't find one that suited my needs. So, I decided to create my own. I implemented a customElement with grid layout, but encountered an issue when trying to assign grid ...

Creating an infinite loop using Jquery's append and setTimeout functions

I'm having trouble displaying my JSON data in a table and refreshing it periodically to check for new entries. Unfortunately, I seem to have gotten stuck in an infinite loop where the setTimeOut function keeps adding old entries. Can anyone help me tr ...

In JavaScript, how does the usage of parentheses change the functionality of a function?

function find() { console.log("Request handler 'find' was called."); } function display() { console.log("Request handler 'display' was called."); } exports.find = find; exports.display = display; There ...

The Videojs controls are unresponsive to clicks

Having a strange issue with videojs. I've been attempting to load videojs in the same way as outlined in the documentation, using a dynamic video tag. videojs(document.getElementById('myVideo'), { "controls": true, "autoplay": false, "prelo ...

The custom directive containing ng-switch isn't being reevaluated when the value is updated

I have developed a unique directive that acts as a reusable form. The form includes an error message display section which utilizes ng-switch: <div ng-switch="status"> <span ng-switch-when="Error" class="text-error">An Error occurred</spa ...

The Node Sass binding for your current environment, which is Linux 64-bit running Node.js 16.x, could not be located

Issue with Module Error encountered in the ./node_modules/sass-loader/dist/cjs.js file: What are the steps to resolve this issue? ...

Learn how to display JSON data sent from the server on a webpage

I'm just starting out with jquery. I have an api called '/categories' that gives me a json object of categories. The response looks like this: [ { name: "Laptop deals", slug: "laptop-deals", imageURL: "image.jpg", id: 1 }, { name: "Fashion ...

Leveraging Next.js for "client-side rendering" in React Encapsulations

My dilemma involves a component housing content crucial for SEO optimization. Here is an excerpt from my code: <AnimatedElement className="flex flex-col justify-start items-center gap-4 w-full" duration={500}> <h2 class ...

Adjust the Width on the X Axis with Three.js

I am currently working with an object in Three.js, which has been exported in JSON format for easier use. I am looking to adjust the width between the X axis of the object without using the scale function, as it affects the angles of the object in ways tha ...

"Stopping the default behavior of an event can impact the remainder of the code

Within this project, there exist three .ejs pages, namely index.ejs, loading.ejs, and result.ejs. The initial page to load is index.ejs, which contains the following code within its script tag: document.addEventListener("DOMContentLoaded", functi ...

Feeling puzzled by the code snippet for vuejs-templates using webpack-simple?

Just starting out with javascript. Learning Vue.js through example reading. But feeling confused by the code snippet from vuejs-templates/webpack-simple. Specifically line 25 data () { return { msg: 'Welcome to Your Vue.js App' ...

Seamless connection through Shopify's Buy Button

I have created a website using HTML5 and I am trying to create a direct link to a product checkout page without all the additional formatting and features that come with BuyButton. Shopify has provided me with this code: <div id='product-component ...

Exploring methods to conduct testing on an AngularJS application using AngularJS end-to-end testing, specifically focusing on scenarios involving multiple inputs

Our program includes a directive that is repeated multiple times with an input field. The structure of our code resembles the following: <li> <label>AMI</label> <div class="searchbox" searchbox="" filter="search.ami"> ...

Why is it that PHP is used to retrieve the database value, JavaScript increments it, and AJAX saves it back to the database, yet it resets to 0.0 upon page refresh?

I am in the process of creating a page for setting temperature targets. The form allows users to adjust the target temperature by increments of 0.5 using JavaScript buttons. Once the user is satisfied with the new target, they can click 'set' whi ...

The property 'createDocumentFragment' is not defined and cannot be read in JavaScript code

I'm working on loading data from my database using ajax, but I'm facing an issue with the this method not functioning as expected. Below is a snippet of my source code: $(".cancel-btn").click(function() { var cancelArea = $('.cancel&apos ...