Prompt for confirmation in ASP.NET code-behind with conditions

I've searched around for a solution to this problem. Below is a representation of my pseudocode:

bool hasData = ItemHasData(itemid);
Confirm = "false"; // hidden variable

if (hasData)
{
    //Code to call confirm(message) returns "true" or "false"
    if (Confirm == "true")
    {
         //Delete item
    }
    else if (Confirm == "false")
    {
         return;
    }
}

The code calling the confirm function uses an asp:Literal control and assigns it the value of the confirmation message. I am able to display the popup, however, it only appears after the execution of the function and does not handle subsequent conditions.

The general consensus is that invoking JavaScript at that specific line is unachievable due to the gap between server-side and client-side operations. How can I work around this? I attempted using the ConfirmButtonExtender from the ASP.NET AJAX Toolkit but encountered issues interacting with the object in the code behind when it is set to runat="server".

Edit:

Apologies for missing those details. Much appreciated, Icarus.

The control in question is the GridView (the pseudo version actually pertains to the gvData_RowCommand function)'s rowcommand. The initial check confirms whether the CommandName is DeleteItem, triggering subsequent actions.

The columns in gvData are determined by a list of headers and dataset; the table caters to multiple items with varying required information. While the data is present, I need a Yes/No (or, more realistically, Ok/Cancel) dialog to confirm deletion intentions when there is existing data.

Answer №1

When faced with certain situations, one approach I often take is to implement a Panel that showcases the Confirm and Cancel buttons. This eliminates the necessity of dealing with JavaScript events and allows for complete utilization of ASP.NET.

<asp:Panel ID="pDeleteConfirm" runat="server"
    CssClass="AlertDialog"
    Visible="False">
    <p>Do you wish to delete the selected record?<br />
    <asp:Button ID="btDeleteYes" runat="server" OnClick="btDelete_Click" Text="Delete" />
    <asp:Button ID="btDeleteNo" runat="server" OnClick="btDelete_Click" Text="Cancel" />
    </p>
</asp:Panel>

<asp:GridView ID="gvData" runat="server"
    AutoGenerateColumns="False" 
    CssClass="GridView"
    DataKeyNames="ID"
    DataSourceID="sqlData"
    EmptyDataText="There is no data entered in the system."
    OnRowDeleting="gvData_RowDeleting">
    ......
</asp:GridView>

The OnRowDeleting event triggers the display of the Panel

protected void gvData_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    // Show confirmation dialog
    pDeleteConfirm.Visible = true;

    // Select the row to delete
    gvData.SelectedIndex = e.RowIndex;

    // Cancel the delete so the user can use the confirm box
    e.Cancel = true;
}

Management of the button Click events

protected void btDelete_Click(object sender, EventArgs e)
{
    Button bt = (Button)sender;
    switch (bt.ID)
    {
        case "btDeleteYes": // they confirmed a delete
            sqlData.Delete();
            break;

        case "btDeleteNo": // they clicked cancel
            // Do nothing
            break;

        default:
            throw new Exception("Unknow button click in btDelete_Click");
    }
    // clear selection and hide the confirm box
    gvData.SelectedIndex = -1;
    pDeleteConfirm.Visible = false;
}

While this doesn't involve JavaScript directly, you can introduce some UpdatePanels for AJAX functionality.

An alternative method using ASP.NET instead of relying on JavaScript for handling.

Answer №2

When your code-behind finishes its job of rendering HTML to the browser, the socket closes and your server-side code stops running.

To achieve this functionality, you will need to use a JavaScript function on the client side.

If you want to notify the user of any loaded data before they perform a specific action or attempt to navigate away from the page, you must display an alert using scripting when that event occurs on the page.

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

Angular alert: The configuration object used to initialize Webpack does not conform to the API schema

Recently encountered an error with angular 7 that started popping up today. Unsure of what's causing it. Attempted to update, remove, and reinstall all packages but still unable to resolve the issue. Error: Invalid configuration object. Webpack ini ...

Using Node.js to separate applications on the same URL based on different paths

We currently have a server hosting one domain, where we have placed apps separately using specific URL paths. For instance, the front-end of our app is mapped to the main URL (/). Requests to / will be directed to the front-end app, while adding /api in ...

Having difficulties showing selectors content in Cheerio

Seeking assistance with extracting a table from a website, specifically trying to retrieve all the columns first. When I make the request and load the html into cheerio, I am facing an issue where the selector content does not display anything on the conso ...

Vuejs is throwing an error claiming that a property is undefined, even though the

I have created a Vue component that displays server connection data in a simple format: <template> <div class="container"> <div class="row"> <div class="col-xs-12"> <div class="page-header"> < ...

Using Regular Expressions in Javascript

I have gone through numerous posts with this title, but so far, none of them have addressed my specific query... My requirement is to utilize regex in the following format: "/^ user provided input $/i". The user can include the special regex character * e ...

Why isn't my React image updating its source right away? What are some solutions to this issue?

I currently have a basic <img> tag with a specified src attribute. <img src={src} /> When I update the src attribute from, let's say /1.jpg to /2.jpg, there is a delay in loading the new image. React still displays the old image (/1.jpg) ...

Running a Chrome content script once an AJAX request has been triggered by the <body> element

I am facing a challenge with running the content script before the DOM is fully loaded. To give context, there is an AJAX request within a tag which gets triggered on $(document).ready(). Once this request is completed, my extension code kicks in. To tra ...

The global variable remains unchanged within an ajax request

Here is the code I am working with: In developing this code, I referenced information about the window variable from here <script> $(window).on("load", function() { function myForeverFunc(){ ...

How to instantly return progress bar to zero in bootstrap without any animations

I am currently working on a task that involves multiple actions, and I have implemented a bootstrap progress bar to visually represent the progress of each action. However, after completion of an action, the progress bar is reset to zero using the followi ...

What is the best approach for managing routing in express when working with a static website?

Whenever a user navigates to mydomain.com/game, I aim for them to view the content displayed in my public folder. This setup functions perfectly when implementing this code snippet: app.use('/game', express.static('public')) Neverthel ...

Conceal a designated column within a material angular data table based on the condition of a variable

In the morning, I have a question about working with data tables and API consumption. I need to hide a specific column in the table based on a variable value obtained during authentication. Can you suggest a method to achieve this? Here is a snippet of my ...

Instead of receiving my custom JSON error message, Express is showing the server's default HTML error page when returning errors

I have set up a REST api on an Express server, with a React app for the front-end. The design includes sending JSON to the front-end in case of errors, which can be used to display error messages such as modals on the client side. Below is an example from ...

Displaying handpicked phrases [Javascript]

When you click your mouse on a sentence, the words inside are highlighted. This feature works flawlessly. However, trying to display the selected words using the button doesn't seem to be functioning as intended. JSFiddle words = []; var sentence ...

Save this code snippet to your clipboard using vanilla JavaScript (no jQuery needed)

I am working on an Angular 9 application where I want to implement the functionality of copying the URL to clipboard when clicked. Currently, I have the following code: The issue I am facing is that it only copies the URL on the second attempt and then st ...

When attempting to send an email using the emailjs.send function, an unexpected error occurred showing the URL https://api.emailjs.com/api/v1.0/email/send with a

import emailjs from 'emailjs-com'; async function sendEmail() { try { const serviceID = '...'; const templateID = '...'; const userID = '...'; const emailParams = { to_email: '...&a ...

The ng-model binding does not automatically update another ng-model within the same object

Check out this code snippet: http://plnkr.co/edit/aycnNVoD96UMbsC7rFmg?p=preview <div data-ng-app="" data-ng-init="names=['One']"> <input type="text" ng-model="names[0]"> <p>Using ng-repeat to loop:</p> <ul> ...

Cypress - A Guide to Efficiently Waiting for the Outcome of a Javascript Function Import

I am interested in creating a Javascript library to act as a wrapper for 3rd party APIs. I have decided to write the API wrapper as a standalone file rather than using Cypress Custom functions, so that I can share the library with teams who are not using C ...

"Efficiently setting up individual select functions for each option in a UI select menu

I've integrated UI Selectmenu into my current project UI selectmenu includes a select option that allows for setting select behavior across all selectmenu options, as shown in the code snippet below: $('.anything'). selectmenu({ ...

The appearance of Recaptcha buttons is unattractive and seemingly impossible to

Let me start by saying that I have already looked into the issue of "Recaptcha is broken" where adjusting the line-height was suggested as a solution. Unfortunately, that did not work for me. After implementing Google's impressive Recaptcha on my web ...

Identify the absence of search results in an Ajax request to the search page before rendering the HTML content

I am attempting to retrieve JSON code from a page using the following PHP function: private function __ajax_admin_search($username = '') { $result = $this->admin_login->Admin_Username_Ajax($username); $count = count($result); for ...