In the realm of asp.net, the OnClick event springs into action after the

My asp button uses OnClientClick to execute a javascript function, and I also want to run OnClick after OnClientClick. However, the OnClick never seems to execute. Despite looking through similar topics on StackOverflow and other websites, I can't seem to get it to work for me.

<asp:Button ID="btn_del" runat="server" Font-Bold="True" Text="DELETE" Width="130px" UseSubmitBehavior="false" OnClientClick="if (!RunDelete()) return false;" OnClick="btn_del_Click" />

function RunDelete() {
        OnDelete("Delete?", function yes() {
            var id = $('#<%=txt_id.ClientID%>').val();

            $.ajax({
                type: "POST",
                url: "/demo.aspx/DeleteRowDb",
                data: JSON.stringify({ "RecordID": id }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert(response.d);
                }
            });
            return true;
            
        },
            function no() {
                return false;
            });
    }

I've attempted to create another button with the same OnClick behavior and tried to trigger it from JavaScript using

document.getElementById('<%= btn_del2.ClientID %>').click();
, but it still doesn't seem to work. I really need the OnClick to execute because I rely on the protected void method in the code behind to function correctly, and I'm limited in what I can do within the public static string function.

Answer №1

Let's break down the process step by step.

Firstly, there is no need for setting submit behaviour to false as we are using a regular button.

The button markup should look like this:

<asp:Button ID="btn_del" runat="server" 
Font-Bold="True" Text="DELETE" Width="130px" 
OnClick="btn_del_Click" />

When the above button is clicked, the code behind function btn_del_Click will be executed.

To add an additional client-side check before executing the code behind function, use OnClientClick.

You can incorporate a confirm dialog in JavaScript to allow or prevent the execution of code behind based on user input.

Your updated button markup with a confirmation prompt would be:

<asp:Button ID="btn_del" runat="server" 
Font-Bold="True" Text="DELETE" Width="130px" 
OnClick="btn_del_Click"
OnClientClick="return myprompt()"
CssClass="btn" />

<script>
function myprompt() {
    return confirm("Really delete this?")
}
</script>

If the user confirms deletion by clicking "OK," the code behind will execute. If they click "Cancel," it will not.

Consider enhancing the default browser dialog appearance by utilizing jQuery.UI for a more polished and customizable experience.

Modify the button markup when incorporating jQuery.UI:

<asp:Button ID="btn_del" runat="server" 
Font-Bold="True" Text="DELETE" Width="130px" 
OnClick="btn_del_Click"
OnClientClick="return myprompt(this)"
CssClass="btn" />

<script>
mypromptok = false
function myprompt(btn) {
    if (mypromptok) {
        return true
    }
    // open jQuery.UI dialog
    var mydiv = $("#mydeldiv")
    mydiv.dialog({
        modal: true,
        appendTo: "form",
        title: "Delete Hotel?",
        closeText: "",
        width: "400px",
        position: { my: 'left top', at: 'right bottom', of: btn },
        buttons: {
            ' ok ': function () {
                mypromptok = true
                btn.click() //trigger button click event again
            },
            ' cancel ': function () {
                mydiv.dialog('close')
            }
        }
    });
    return false
}
</script>

<div id="mydeldiv" style="display:none">
    <h3><i>Delete this Hotel</i></h3>
    <h4><i>This action cannot be undone</i></h4>
</div>

By implementing these changes, a sleek jQuery.UI dialog appears near the button click location, providing a modern feel to the interaction.

These concepts can also be applied to scenarios involving grids and multiple row operations with deletes.

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

Tips for transferring information between two distinct ports within a single application

I have been utilizing the expressjs library for my project. It functions as a server on localhost:8000 and I am displaying static pages through it. However, my application operates on localhost:4200. Despite attempting to share the same cookie or localSt ...

Where in the page life cycle can session state and application state be found?

When does session state and application state come into play during the page life cycle? ...

Issue with JQuery form submission causing controller method not to be executed

I am facing an issue with two click methods in my JavaScript code. Method 1 is successfully hitting the controller method, but when I try to trigger Method 2 by clicking on a button, it does not seem to call the controller. I have tried various solutions ...

Obtaining output values from a POST request

When making a GET request through Ajax using jQuery, the URL displayed in the Chrome console is script.php?param=1. $.ajax({ type : "POST", url : "script.php", data : { q : "save", query : query // a variable }, succe ...

Struggling to Parse JSON Responses?

Utilizing AJAX/JQuery to communicate with a WCF service presents its own set of challenges. One common method is implementing .NET try/catch error-handling on the service-side to manage different scenarios, such as user timeout errors. Typically, the servi ...

What is the process for incorporating the !important declaration into a CSS-in-JS (JSS) class attribute?

I'm currently exploring the use of CSS-in-JS classes from this specific response in conjunction with a Material UI component within my React project. In order to override the CSS set by Bootstrap, I've decided to utilize the !important modifier. ...

Most efficient method to upload numerous images without any lag

I have a website where images are loaded only when they are slightly below the viewport. This method allows the site to load initially without images and then determine which ones need to be loaded based on the user's viewpoint. When a user scrolls ...

Removing the element generated by Angular from the DOM

I've hit a roadblock with this issue. Here is the delete function in my mainController. $scope.delete = function($posts) { $http.delete('/api/posts/' + $posts._id) .success(function(data) { // remove element from DOM ...

Can we trust the accuracy of the official type definition for JSON.stringify?

Upon reviewing the official type definition for JSON.stringify, it appears that it states JSON.stringify always returns a string, even when passed undefined. interface JSON { stringify(value: any, /*...*/): undefined; } However, executing JSON.stringif ...

Synchronize the scrolling of two tables sharing a common data source to ensure both tables scroll in unison

I encountered some issues while using ui-scroll in my application. My goal is to have ui-scroll function on the same datasource that is used to populate two tables. By scrolling one table, I want the other table created from the same data source to also s ...

The latest Asp.net event for uploading files

Currently, I have implemented a file-upload feature on my website which includes an "upload" button and a "Status" indicator. When a file is successfully uploaded, the label's content switches to "File uploaded". However, if a user wishes to upload an ...

Why am I receiving a null response from my ajax request?

I have a working ajax call to fetch XML data from my REST API. However, when I try to echo the results, JQuery returns null. If I use var_dump on the results instead, JQuery accepts the information but it's not formatted correctly and causes errors. ...

What is the best way to execute a function individually for every tag within a vue.js application?

I'm currently exploring the world of Vue JS and I thought it would be interesting to experiment with something new. Sometimes looking at the code first makes understanding it much easier than a lengthy explanation. Check out this code snippet on jsFi ...

Safari iOS 8 experiencing issues with loading WebGL image textures

The example mentioned above runs smoothly on all major browsers, including Safari on Mac OS. However, it fails to display the correct image on my iPad running the latest iOS 8. Click here for the example. Similarly, the tutorial provided in the following ...

Dynamic translation routing with Next.js

My goal is to create dynamic translation routes for specific pages in next js using i18next. While the following code works well, it currently routes to all pages and generates errors during next build. const router = useRouter(); const path = router.route ...

Jquery draggable droppable does not support displaying multiple divs simultaneously

I tried to implement the jquery ui draggable and droppable features to display 3 divs within a designated area. Below is the code snippet: --CSS: #content-1 { width: 200px; height: 100px; border: 1px solid red; display: none; } #content-2 { width: ...

The textgeometry element is not appearing in the three.js scene

I've inserted a boxgeometry into the scene with the intention of adding text to indicate the side of the cube. However, I am encountering difficulties in incorporating textgeometry into the scene. This is my code: const loader = new FontLoader(); loa ...

Using knockout to bind JSON data

I have a table that is supposed to be bound with the result of a JSON object: <table> <thead> <tr> <th> Id </th> <th> Number </th> <th> ...

React component is being rendered, but it is not mounting properly, so it is unable

In my FillForm functional component, I am calling a list of objects to be rendered sequentially within the FormFiller function. The components are rendering correctly, but I encounter an error when trying to change their internal state. Warning: Can&apos ...

A guide to effortlessly converting Any[] to CustomType for seamless IntelliSense access to Properties within Angular/Typescript

Our Angular service interacts with the backend to retrieve data and display it on the UI. export interface UserDataResponse { id: number; userName: string; } AngularService_Method1() { return this.http.get<UserDataResponse[]>(this.appUrl + "/Ap ...