What is the method to trigger a confirmation message from the backend code in ASP.NET?

Hello, I am looking to trigger a client-side JavaScript confirm message from the code-behind in ASP.NET.

I need to capture the true or false return value from the confirm message.

Currently, I am attempting to do this using the following method, but it seems to be incorrect. Can someone please guide me on how to achieve this correctly?

ScriptManager.RegisterStartupScript(this, this.GetType(), "myconfirm", "confirm('No Rule Type Ids found for This Rule.');", true);

Answer №1

Here is a solution that may help you achieve your goal:

<script type = "text/javascript">
        function Confirm() {
            var confirm_value = document.createElement("INPUT");
            confirm_value.type = "hidden";
            confirm_value.name = "confirm_value";
            if (confirm("Do you want to save data?")) {
                confirm_value.value = "Yes";
            } else {
                confirm_value.value = "No";
            }
            document.forms[0].appendChild(confirm_value);
        }
    </script>

.aspx code

<asp:Button ID="btnConfirm" runat="server" OnClick = "OnConfirm" Text = "Raise Confirm" OnClientClick = "Confirm()"/>

C#

public void OnConfirm(object sender, EventArgs e)
{
    string confirmValue = Request.Form["confirm_value"];
    if (confirmValue == "Yes")
    {
        this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked YES!')", true);
    }
    else
    {
        this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked NO!')", true);
    }
}

Answer №2

Instead of coding the confirmation directly, you can call a JavaScript function by its name. For example:

ScriptManager.RegisterStartupScript(this, this.GetType(), "myConfirmFunction", "displayConfirmationDialog();", true);

In your JavaScript file, define the function displayConfirmationDialog:

<script>
function displayConfirmationDialog() {
    if (confirm('Are you sure you want to proceed?')) {
        // True - perform some action
    } else {
        // False - perform some other action
    }
}
</script>

Answer №3

It's important to remember that client-side code, like JavaScript, cannot be mixed with server-side code. The server-side code must finish processing before the client (browser) receives the client-side code.

If you encounter this issue, consider halting processing to display a question or redirecting the user to another page. Once confirmed by the user, you can proceed with your processing.

Answer №4

Let's generate a JavaScript prompt to ask the user if they want to create a new record for a non-existent vehicle:
<script language=javascript>
    Response.Write("if(confirm('The vehicle does not exist, Would you like to create the entry?')){window.location.href='IngresoVehiculos.aspx'}");
</script>

Answer №5

employ:

Response.Write("<script>alert('Display Message!');</script>");

Answer №6

It is possible to achieve this without the need for a JavaScript function.

Give this a shot:

if (MessageBox.Show("confirm('No Rule Type Ids found for This Rule.')",
            "myconfirm", 
            MessageBoxButtons.YesNo) == DialogResult.Yes)
    {
        // Action if yes
    }
    else
    {
        // Action if no
    }

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

Receive a sibling from a specified node

Looking for a solution to navigate through an XML file like this: <material> <item> <name>theName1</name> <val1>1.1</val1> <val2>2.5</val2> <val3>5.2</val3> </it ...

What is the best way to transfer data from a controller to a router in a node.js application

I have a folder structure with two files: a controller and a router. I have successfully pulled data from MongoDB in the controller, but I am having trouble passing it to the router in order to send it to the client using an API. Any ideas on what might be ...

Angular Module Federation -- The shared module is currently inaccessible for immediate use

Encountering a problem while attempting to execute tests on my Angular microfrontend for use within Module Federation. Using Angular 12 and Webpack 5. Uncaught Error: Shared module is not available for eager consumption: 5487 Any suggestions on how to co ...

Show live updates in the input field

I'm struggling to get an input's results to update in real time within another disabled input field. Here is the code I'm working with: var inputBox = document.getElementById('input'); inputBox.onkeyup = function(){ document. ...

Acquiring a DataRowCollection

Is it possible to sort a DataRowCollection in ASP.NET WebForms like we do with a List in ASP.NET MVC? public DataRowCollection GetSortedRow(DataRowCollection dataRows) { var sortedResult = dataRows.OrderBy(d => d["Name"]) } Unfortunate ...

Error encountered during NextJS build - file or directory not found for 500.html

I recently made the switch from Page Router to App router. Transitioning pages - 500.tsx to app - 500 - page.tsx However, I encountered an error when running yarn build/next build: > Build error occurred [Error: ENOENT: no such file or direc ...

Create an array of property names by passing object properties

I have a situation where my class has numerous properties and I need to send these property names to a webservice. The simple solution would be to manually create an array, like new[] {"Id", "Name", "Date", "etc"}. However, I'm looking for a more ...

Efficiently Delivering Model Object to View in Asp.Net MVC through Ajax Requests

Check out the following code: @model IEnumerable<InfinityWeb.Models.Orders> <body> foreach(var item in Model) { <label> item.OrderId </label> <br/> @* it display all students name *@ } @* Below is just DropD ...

Guide on making an SVG tooltip using the Menucool JS extension

I am trying to add a simple tooltip to an SVG "map" when the mouse hovers over a rectangle. To create the tooltip, I would like to utilize this specific plugin. Here is how I have connected the SVG to HTML: <object data="map.svg" type="image/svg+xml" ...

Struggling with the alignment of pictures inside a container

I utilized the Instafeed.js library to fetch the three most recent images from an Instagram account. These images are loaded into a specific div and I successfully customized their styling according to my requirements. However, the current setup is quite s ...

Choose and activate a button using a CSS selector in Selenium with C#

Can someone guide me on how to select and click a button on a webpage using Selenium? The specific source code I am referring to is shown below: <span class="login-bt"> <a href="#" onclick="return sChangeURL('GB2101_KAIINLOGIN','h ...

Troubleshooting problems with callback functionality in conjunction with Expressjs, JWT authentication, and Angular

For my current project, I am implementing authentication using JWT with Expressjs and Angularjs. However, I now need to integrate node-dbox to access Dropbox files of my users. The issue arises when trying to store the token received from Dropbox for user ...

Prevent clicking on the <div> element for a duration of 200 milliseconds

I need to make this box move up and down, but prevent users from clicking it rapidly multiple times to watch it go up and down too quickly. How can I add a 200 millisecond delay on the click or disable clicking for that duration? View the jsfiddle example ...

Tips for saving React console logs to a server

We are looking to understand the root cause of the issue occurring on the client side and figure out a way to store client console logs on the server side. How often should we send these logs to the server for storage? We also want to make sure that when ...

Show live data in JQgrid on Codeigniter platform

I'm currently working on a project using CodeIgniter that involves implementing a JQgrid table to display data. While I am able to retrieve the data from the database, I have encountered difficulties in displaying it within the JQgrid itself. However, ...

What is the best way to remove all selected items in a dropdown menu?

My issue pertains to Angular and Typescript. I am facing a challenging problem with a dropdown menu that has 3 items. The unique aspect is that I am not utilizing the standard select HTML tag; instead, I am using my company's custom toolkit, which ser ...

Troubleshooting a ForwardRef issue in a TypeScript and React Native project

Encountering a ts error while using forwardRef. // [ts] Property 'forwardRef' does not exist on type 'typeof React'. const MyComponent = React.forwardRef((props: Props, ref: any) => ... An issue arises in React Native when the pare ...

Error encountered due to an incorrect expression term

When trying to replace the word "test" with "Atest" in my VS2013, .NET 4.5.1 code, it resulted in an error as shown above: return Regex.Replace("This is test. Another test.", "test", "A" + m => m.Value); However, replacing "test" with "testA" worked u ...

Ways to incorporate a loading feature in javascript, jquery, and php as it runs?

I have created a form that, when clicked on, returns a value within the page. Below is my form. When the form is submitted, it takes some time to process. I would like to display a loading message while the code is being executed. Here is my form: <ht ...

Issue encountered in Three.js related to the THREE.ObjectLoader

Help Needed with Three.ObjectLoader. I am exporting a scene in JSON Format 4.3, containing geometries, materials, and lights. The scene opens error-free in the Three.js Editor. Working on firefox with Three.js r70 master. View the generated json here: htt ...