简体   繁体   中英

How to handle client-side confirm in code behind?

I have a vb.net project where I need to ask to the user to confirm some action. My problem is that, rigth now I can show the confirm dialog to the user, but I can't get the response in the code behind. Based on this post I can show the confirm dialog and do some stuff according to response, but the problem with that solution is that I need to show, in the dialog a list of data from a database, so the javascript code must be handled, also, from the codebehind.

Here is my code to show the confirm dialog

'myPage.aspx.vb
Private Sub ConfirmBox(ByVal message As String)
    Dim sb As New System.Text.StringBuilder()
    sb.Append("<script type = 'text/javascript'>")
    sb.Append("window.onload=function(){")
    sb.Append("var confirm_value = document.createElement(""INPUT"");")
    sb.Append("confirm_value.type = ""hidden"";")
    sb.Append("confirm_value.name = ""confirm_value"";")
    sb.Append("if (confirm("" " & message & " "")) {")
    sb.Append("confirm_value.value = ""Yes"";")
    sb.Append("} else {")
    sb.Append("confirm_value.value = ""No"";")
    sb.Append("}")
    sb.Append("document.forms[0].appendChild(confirm_value);")
    sb.Append("};")
    sb.Append("</script>")
    ClientScript.RegisterClientScriptBlock(Me.GetType(), "alert",   sb.ToString())
End Sub

That show the dialog, and, based on the user click, insert a hidden input with the value I'm lookin for to be retrieved, I can get that value like this string confirmValue = Request.Form["confirm_value"]; . But after the confirm is shown it ask inmediatly for the response, and, obviously, the user hasn't clicked anything yet.

So, can you help me to get the user confirmation and do something based on that confirmation?

You have to consider where the code is executing and in what order. You can't directly get the value from a JavaScript confirm() dialog into a code behind. You'd have to capture that value in JavaScript, then store the value in a hidden field, then initiate a postback, and read that from the form.

Ususualy if you want to confirm, it's after clicking a button but before the postback has been performed. And often you want to cancel the postback if the user declines. You can easily accomplish this by returning a value from the OnClientClick attribute. A return value of false will cancel the postback before it starts.

<asp:Button runat="server" id="Btn1" OnClick="Btn1_Click" OnClientClick="return confirm('Are you sure you want to do this?')" Text="Click Me" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM