Javascript confirm message problem

user175084 picture user175084 · Feb 9, 2011 · Viewed 20.6k times · Source

I have a popup confirm box which i am able to show like below.

But i dont know if the user clicked ok or cancel.

                ScriptManager.RegisterStartupScript(this, this.GetType(), "ajax", "<script language='javascript'>confirm('Do u wanna change?');</script>", false);

so what i want to do is like this.

if (orignalId != newId)
                {
 ScriptManager.RegisterStartupScript(this, this.GetType(), "ajax", "<script language='javascript'>confirm('Do u wanna change?');</script>", false);

If (user clicks Yes)
{
add some data to SQL
}
else
{
return;
}
}

How do i Know what the user has clicked??

i have tried this

  1. i put the code below in a folder1\jscrip.js file but i dont kno how to call it as i have a used ajax update panel in the page so i cannot use ClientScript.RegisterClientScriptInclude to reference it. as mentioned in the 6th point at this link: http://www.dotnetcurry.com/ShowArticle.aspx?ID=274

Page.ClientScript.RegisterClientScriptInclude("selective", ResolveUrl(@"folder1\jscrip.js"));

function confirmation()
{
if(confirm("Are you sure?")==true)
return true;
else
return false;
}

Any suggestions???Thanks

functionality:

so the user clicks a button called "Save first" then in that it checks the condition "if (orignalId != newId)" if it is true the confirm box is shown or else no confirm box is shown.. now if the user clicks OK some values are enterd in DB or else it just returns and does nothing

some extra code:

protected void Page_Load(object sender, EventArgs e)
        {
if (!IsPostBack)
            {
            }
 else if (Label.Text != "")
            {
                Global.logger.Debug("Postback Happ, Label = " + Label.Text);
                Button2_Click(sender, e);
            }
        }

 protected void Button2_Click(object sender, EventArgs e)
        { if (orignalCsId != 0 && newCsId != 0)
                {
                    if (orignalId != newId)
                    {
                        Global.logger.Debug("Pop Up crossed1");
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "ajax", String.Format(CultureInfo.InvariantCulture, @"__doPostback('{0}', confirm('Your Data From iD1 will be populated in iD2?').toString());", Label.Text), true);
                    }
                    else if (Page.Request["__EVENTTARGET"] == Label.Text)
                    {
                        Global.logger.Debug("__EVENTARGUMENT1 = " + Page.Request["__EVENTARGUMENT"]);
                        bool userClickedOK = Boolean.Parse(Page.Request["__EVENTARGUMENT"]);
                        if (userClickedOK)
                        {
                            // Add some data to SQL.
                        }
                        else
                        {
                            return;
                        }
                        Label.Text = "";
                    }
                }
          }

Answer

Fr&#233;d&#233;ric Hamidi picture Frédéric Hamidi · Feb 9, 2011

You could use a hidden field, but you would still have to force a postback after the user dismisses the confirm box. Since you will end up calling __doPostBack() anyway, you can take advantage of its second argument to post the return value of confirm() back to the server without using a hidden field:

if (originalId != newId) {
    ScriptManager.RegisterStartupScript(this, GetType(), "ajax",
        String.Format(CultureInfo.InvariantCulture, @"
            __doPostBack('{0}', confirm('Are you sure?').toString());
        ", yourUpdatePanel.ClientID), true);
} else if (Page.Request["__EVENTTARGET"] == yourUpdatePanel.ClientID) {
    bool userClickedOK = Boolean.Parse(Page.Request["__EVENTARGUMENT"]);
    if (userClickedOK) {
        // Add some data to SQL.
    } else {
        return;
    }
}

First, we compare the two ids. If they're different, we need to show a confirm box on the client and post its result back to the server, so we include a startup script to do that (note that you can pass true as the last argument to RegisterStartupScript() in order to have it generate <script> tags for you).

Then, on the client side, we need to call __doPostBack() to force a postback after the blocking call to confirm() returns. __doPostBack() takes two arguments: the ClientID of the control that initiated the postback (the event target), and an optional event argument. They're used by the internal ASP.NET plumbing in order to raise postback events, but that doesn't mean we can't use them to our advantage.

Moreover, if a postback occurs and an UpdatePanel is the event target, the aforementioned ASP.NET plumbing will only refresh that panel (or more, depending on their UpdateMode properties, but that's another subject). So we call __doPostBack() with the ClientID of the UpdatePanel containing the controls we want to refresh, and the return value of confirm(), converted to a string.

Back to the server side, the page is reloaded, and our code runs again. Since you implied in your question's comments that if originalId and newId are still different, we'll have to show the confirm box again, I assume they will be the same this time around (the else if ensures that).

The arguments passed to __doPostBack() are accessible server-side from the __EVENTTARGET and __EVENTARGUMENT request variables. So first, we check if the event target is our UpdatePanel, and if that's the case, we know we're handling a forced postback and the value of __EVENTARGUMENT is meaningful. So we call Boolean.Parse() to deserialize it from the string we generated earlier on the client side, and use it to decide whether or not to update the database.