Skip to content Skip to sidebar Skip to footer

Display A "Yes / No" Alert Box In C# Code Behind

I am trying to display a 'Yes / No' messagebox from codebehind in C#. I want to call an 'AddRecord' procedure if the user clicks 'Yes', and do nothing if the user clicks 'No'. I

Solution 1:

on your Add Record button, just do the following:

    <asp:button ID="AddRecordbutton" runat="server" Text="Add Record"
 onclick="AddRecordButton_Click" onclientclick="return confirm('add record?');" />

In your code behind, just put the add record code in your AddRecordButton_Click event handler. It will only be called if they click Yes on the popup.


Alternatively, you could have your codebehind assign the onclientclick code when the button is initially rendered.

For example:

protected void Page_Load(object sender, EventArgs e) {
  AddRecordButton.OnClientClick = @"return confirm('Add Record?');";
}

Solution 2:

No, you don't.

You seem to be misunderstanding that basic concept of webpage.

An ASPX page is a short program, which starts-up, generates seem HTML, and then terminates. The HTML is then sent across the Internet to the users browser. EVERYTHING you do in a codebehind must be complete before the user ever sees any of it.

You really want a javascript dialog box. (Actually, from what you describe, you could just create a messagebox-looking div in HTML with a standard HTML form on it.)


Solution 3:

To display an actual messagebox you will need javascript as it is done on the client-side. For whatever reason, if you cannot use javascript, you could do what AEMLoviji has suggested and "fake" it with some cleverness.

Note that you do not need jQuery to display a messagebox, simple javascript will suffice.


Solution 4:

If you use the Ajax Control Toolkit Modal Popup Extender on a Panel with your two buttons this will fire an event on the server which can be handled and execute whichever method/functions you wish

See here for an example


Solution 5:

Use RegisterStartupScript

ScriptManager.RegisterStartupScript(this, GetType(), "unique_key",
    "element.onclick = function(){ return confirm('Are you sure you want to delete?'); };",
    true);

Post a Comment for "Display A "Yes / No" Alert Box In C# Code Behind"