Javascript confirm message problem

2020-03-26 05:26发布

问题:

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 = "";
                    }
                }
          }

回答1:

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.



回答2:

Use the Hidden field in your page and set the value to true of false once the user confirms or not. Then @ server side check the value of your hidden field IF It was true continue the process If not use return or exit sub.

function confirmDelete()
{

    var x = confirm("Are you sure you want to Delete?");
    if (x)
    { 
        document.getElementById('Hidden1').value = "True";
    }
    else
    {
        document.getElementById('Hidden1').value = "False";
    }
}

Server Side

if (orignalId != newId)
                {
 ScriptManager.RegisterStartupScript(this, this.GetType(), "ajax", "<script language='javascript'>confirmDelete();</script>", false);

If (Hidden1.value=="True")
{
add some data to SQL
}
else
{
return;
}

}



回答3:

I know it's been a while since this question has been asked, but I wanted to chime in in case anyone is still searching for a concise, simple answer. If you're looking for a client side javascript popup to confirm (yes or no, yes or cancel, etc.) a server side function like deleting a db item, the simplest route I've found was to use the OnClientClick parameter in your asp:button or asp:linkbutton in your markup:

<asp:LinkButton Text="Delete" ID="DeleteProj" runat="server" CommandName="deleteproj" OnClientClick="return confirm('Are you sure?');" CommandArgument='<%# Eval("ProjectID") %>'/> 

Clicking no will send user back to your page, clicking yes will run whatever C# codebehind you have set up for it. This worked for me.



回答4:

ScriptManager.RegisterStartupScript often tends to block a popup . If you try the approach in the below link you will have complete control on every single click with in a popup.

http://02e34b5.netsolhost.com/youtube/Zpopup.aspx

This popup doesn't need any ajax, javascript, jquery or css trick but gives you complete control.