Search code examples
c#jqueryconfirm

Conditional confirm box in c#


How to call a conditional confirm box from c#.

I have 2 hidden fields and based on the condition I want to call confirm box.

After that I also want what user has pressed (clicked on yes or No).

Design:-

  <input type="submit" id="btnAddPaymentMethod" onserverclick="AddPaymentMethod_Click" runat="server" value="add payment method" />

Code:-

   protected void Next_Click(object sender, EventArgs e)
     {
            if (hdnDefault.Value == hdnPrimary.Value) { return; }
            else
            {
            //open confirm box 
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "confirm", "confirm('Do you want to save new default payment method?');", true);
                    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);
                    }
            }
     }

I have tried below jQuery Code:-

 function Confirm(msg) {
            var confirm_value = document.createElement("INPUT");
            confirm_value.type = "hidden";
            confirm_value.name = "confirm_value";
            if (confirm(msg)) {
                confirm_value.value = "Yes";
                $('#btnAddPaymentMethod').click();
            } else {
                confirm_value.value = "No";
            }
            document.forms[0].appendChild(confirm_value);
        }

Solution

  • protected void Next_Click(object sender, EventArgs e)
    {
      if (hdnDefault.Value == hdnPrimary.Value) { 
        return; 
      } else {
        //open confirm box 
        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "confirm", "Confirm('Do you want to save new default payment method?');", true);
      }
    }
    
    protected void AddPaymentMethod_Click(object sender, EventArgs e)
    {
      string confirmValue = Request.Form["confirm_value"];
      if (confirmValue == "Yes") {
        ScriptManager.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked YES!')", true);
      } else {
        ScriptManager.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked NO!')", true);
      }
    }
    
    function Confirm(msg) {
      var confirm_value = document.createElement("INPUT");
      confirm_value.type = "hidden";
      confirm_value.name = "confirm_value";
      confirm_value.value = confirm(msg)? "Yes" : "No";
      document.forms[0].appendChild(confirm_value);
      $('#btnAddPaymentMethod').click();
    }