Extension ConfirmButtonExtender

There is a scenario where I need to skip the ConfirmButtonExtender based on the value of another field in the page.

Typically, when a user clicks on my "Cancel" button, a modal popup appears using the confirmbuttonextender and the modalpopupextender. The dialog box confirms whether they want to cancel any changes made and return to the previous screen. If they click Yes, the onclick event of the button triggers some code in the codebehind and redirects the user to another page. If they click no, it just reloads the same page without any changes.

However, for certain users who are not allowed to make edits, I do not want to display the "Are you sure you want to leave, you will lose any changes" dialog box.

I have created a hidden checkbox field called "cbAllowEdit" to indicate if the user can edit fields or not.

I tried following a technique mentioned at this link to achieve this but it seems that the button's onclientclick event doesn't fire at all.

Below is the code snippet:

ASPX & Javascript

<asp:CheckBox ID="cbAllowEdit" runat="server" Checked="true" />
         <asp:Button ID="btnCancel" runat="server" CausesValidation="false" 
    OnClick="btnCancel_Click" Text="Cancel" OnClientClick="disableSubmit();return false;"  />
<ajaxToolKit:ConfirmButtonExtender ID="ConfirmButtonExtenderbtnCancel" 
    runat="server" DisplayModalPopupID="ModalPopupExtenderbtnCancel" 
    TargetControlID="btnCancel" BehaviorID="ConfirmButtonExtenderbtnCancel" />
<ajaxToolKit:ModalPopupExtender ID="ModalPopupExtenderbtnCancel" runat="server" 
    BackgroundCssClass="modalBackground" CancelControlID="btnCancelCancel" 
    OkControlID="btnConfirmCancel" PopupControlID="ConfirmCancelPanel" 
    TargetControlID="btnCancel" />
<asp:Panel ID="ConfirmCancelPanel" runat="server" CssClass="modalWindow" 
            Height="200" Width="450">
            <p class="confirmMessage">
                Are you sure you want to navigate away from this record?
            </p>
            <div align="center">
                <p class="feedbackError">If you have made any changes to the record since the last time
                you saved, they will be lost.</p>
                <asp:Button ID="btnConfirmCancel" runat="server" Text="Yes" Width="75" />
                <asp:Button ID="btnCancelCancel" runat="server" Text="No" Width="75" />
            </div>
        </asp:Panel>
        <script type="text/javascript">
            function disableSubmit() {
                if (document.getElementById('<%= cbAllowEdit.ClientID %>').checked) {
                    return checkSubmit();
                }
                else {
                    return true;
                }
            }

            function checkSubmit() {

                var confirmButton = $find('ConfirmButtonExtenderbtnCancel');

                confirmButton._displayConfirmDialog();

            }
        </script>

Code behind:

/// <summary>
        /// Runs when the btnCancel button is clicked.
        /// </summary>
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Page.Response.Redirect("~/Searches/LookupCode/Default.aspx");
        }

Any suggestions on what might be going wrong?

Answer №1

In agreement with Chris, it is not necessary to use both ConfirmButtonExtender and ModalPopupExtender (although this method seems to be a workaround for the limited functionality of the JavaScript confirm() function which only offers OK and Cancel buttons in its dialog - something worth considering for future reference :-) )

If you are confident that there will be no need for editing based on your code-behind logic (as indicated by your cbAllowEdit control), then simply disabling the ConfirmButtonExtender should suffice:

ConfirmButtonExtenderbtnCancel.Enabled = false;

By doing so, clicking the Cancel button will directly execute your code-behind function without any confirmation prompt.

Answer №2

UPDATE: The ConfirmPopupExtender should not be connected to the btnCancel. Instead, it needs to point to a hidden button as demonstrated in the example provided in the link.

<asp:Button ID="btnCancel" runat="server" CausesValidation="false" 
    OnClick="btnCancel_Click" Text="Cancel" OnClientClick="disableSubmit();return false;"  />
<!-- Add these Hidden Buttons and reference them in the ConfirmButtonExtender -->
<asp:Button ID="HiddenButtonConfirm" runat="server" Text="" style="display:none;" />
<asp:Button ID="HiddenButtonModal" runat="server" Text="" style="display:none;" />
<ajaxToolKit:ConfirmButtonExtender ID="ConfirmButtonExtenderbtnCancel" 
    runat="server" DisplayModalPopupID="ModalPopupExtenderbtnCancel" 
    TargetControlID="HiddenButtonConfirm" BehaviorID="ConfirmButtonExtenderbtnCancel" />
<!-- Remember to connect the ModalPopup to a separate hidden button as well. -->
<ajaxToolKit:ModalPopupExtender ID="ModalPopupExtenderbtnCancel" runat="server" 
    BackgroundCssClass="modalBackground" CancelControlID="btnCancelCancel" 
    OkControlID="btnConfirmCancel" PopupControlID="ConfirmCancelPanel" 
    TargetControlID="HiddenButtonModal" />

Answer №3

Try this snippet of javascript code:

var confirmButton = $find('ConfirmButtonExtenderID');

confirmButton.enabled = false;

//Make sure to replace 'ConfirmButtonExtenderID' with the actual ID of your ConfirmButtonExtender [:$]

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

Error: Unhandled promise rejection - The function get is not part of this.categoryMap

I am facing an issue with calling functions of the Map (get, set, keys, etc) within my function. The map I am working with is returned from a firebase query. Here's a snippet of my code: categoryMap = new Map<Number, String>(); //called onInit ...

Picking a specific record from MySql in C# ASP.NET Core without using an id

I'm attempting to retrieve a user from a MySQL table using their username instead of the id in ASP.Net Core. By default, the column used in the GET method is the id. I attempted to modify it to use the username, but the column is unrecognized. Within ...

Discovering Ajax-powered websites Here are some tips on identifying websites

My goal is to determine if a webpage makes AJAX calls. If the webpage is AJAX-based, I will wait for a few seconds to retrieve the content. If it's not AJAX-based, then I won't wait. I attempted the code below, but it didn't yield any resul ...

Utilizing Highcharts to create visually engaging data plots within a Flask-powered web application

I am trying to fetch data from a MySQL server and display it on a web server using the Highcharts JavaScript library for plotting. I have successfully retrieved the data from the MySQL database and sent it from the server-side to the client-side as JSON da ...

Upon attempting to send a POST request with PostgreSQL, the following error is displayed: "Invalid input syntax for type integer: '12 Pro'"

I encountered an error while attempting to send a POST request using PostgreSQL/Sequelize. Can anyone help me identify the issue in this code? async create(req, res, next) { try { let { name, price, brandId, typeId, info } = req.body; c ...

I need the language chosen using Lingui's Language Switcher (i18n) to persist throughout the app, even after a refresh

I have been experimenting with Lingui for internationalization (i18n) in my app. I followed the documentation and tutorial to create a language switcher, but I am unsure how to set it up so that the selected language persists throughout the app even after ...

The alternating colors in the sorting table are not visible due to the divs being hidden with the display set

I've come across a problem that has me stumped. So, there are two sorting filters on a table and one of them hides rows that don't apply, messing up the alternating colors. Take a look at the function that sorts and the CSS below. The issue is pr ...

What is the best method for creating a 10-page PHP form that contains more than 100 input fields in an efficient manner?

I am currently in the process of constructing a substantial PHP form that will extend over 10 pages and contain well over 100 input fields. Each input will be stored in a database. I am starting to encounter challenges keeping track of all the variables as ...

The Discord OAuth2 bot fails to assign roles to authenticated users

While working on OAuth2 login for my website, I encountered an issue. After a user successfully logs in through OAuth2, the bot should assign a role to them on my Discord server. However, when I tested the login process myself, the bot returned an error me ...

Simulating a traditional table scroll function on a window using virtualization

I am currently attempting to incorporate a virtualized table in react using react–virtualized, but I am facing issues with the rendering of the table. I am seeking to understand the root cause for this problem as well as find solutions for other overlapp ...

Creating an Editor for Input Text Field in HTML: A Step-by-Step Guide

In the vast landscape of JS libraries that can achieve this function, like Trumbowyg and more. However, prior to my rails project displaying that slim version, I need to ensure JavaScript is properly escaped! Therefore, I need to create an editor using o ...

Display a component just once in React or React Native by utilizing local storage

I am struggling with a situation where I need to display a screen component only once using local storage. It's really frustrating. App.js ... constructor(props) { super(props); this.state = { isLoading: false, }; } component ...

Creating custom mesh Morph Target Animations using THREE.js

I'm currently working on creating an animation that showcases the revolution of a 2D function around an axis to produce a 3D surface. Successfully rendering the surface, my next task is to implement the animation section using MorphTargets. Despite m ...

Ensuring the accuracy of user input

Can someone assist me with comparing two dates in JSP? I need validation that alerts the user when a future date is entered. The start date or end date should not be in the future. The date format is 12-5-2011 10:51:49. Any help would be greatly apprecia ...

Sending an event to a component that has been rendered in Vue

I'm currently in the process of developing a custom rendered component that will execute a function when clicked on: // Creating a standard Vue component with a render function Vue.component('greeting', { methods: { sayHello(){ ...

Is there a way to prevent the jsonPayload in stackdriver from automatically converting to a struct format?

When working with a Google Cloud Function, I am logging a simple JSON structure like this: console.info(JSON.stringify({message: 'xxx', data: {status: 200}, status: 200})); However, the log appears in an unreadable format in Stackdriver. How ca ...

Trouble with mobile compatibility for .json file content population in HTML elements script

Check out THIS amazing page where I have a series of placeholders for phone numbers in the format: 07xxxxxxxx. By simply clicking the green button "VEZI TELEFON", each placeholder in the green boxes gets replaced with a real phone number from a JSON file u ...

Uploading videos to a single YouTube channel using the YouTube Data API

I have been tasked with creating a node js app for a select group of individuals who need to upload videos. However, our budget is quite limited and we are unable to afford cloud storage services. I am curious if it would be feasible to create a key syste ...

Sequential cascade filtering without a preset default option

Please note: The following code snippet has been adjusted and is now functional. In a MySQL database table, I have the following columns with corresponding values: Category (Fruit, Vegetable) Type (Apple, Orange, Pumpkin, Potato) Subtype (Red Delicious, ...

Ways to dynamically emphasize text within ngFor loop

Within my ngFor loop, I have a set of rows. <div *ngFor="let block of data;"> <div class="class-row"> <div class="left">A Label:</div> <div class="right">{{block.key1}}</div> </div> <div class="clas ...