确认消息框无法正常工作

时间:2017-03-11 22:47:56

标签: javascript c# asp.net messagebox confirm

以下代码在Asp.Net上运行一个确认消息框,但是没有 如果确认与否,我需要检测该值 我怎么能这样做?

Aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type = "text/javascript">
        function Confirm() {
            var confirm_value = document.createElement("INPUT");
            confirm_value.type = "hidden";
            confirm_value.name = "confirm_value";
            if (confirm("Do you want to save data?")) {
                confirm_value.value = "Yes";
            } else {
                confirm_value.value = "No";
            }
            document.forms[0].appendChild(confirm_value);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Button ID="btnConfirm" runat="server" OnClick = "OnConfirm" Text = "Raise Confirm" OnClientClick = "Confirm()"/>
    </form>
</body>
</html>

背后的代码

protected void OnConfirm(object sender, EventArgs e)
{
    // This method runs even though the user clicks no.   
}

更新
使用此代码,yes或no选项都运行名为OnConfirm的相同方法。 所以我尝试运行OnConfirm方法only if the user clicks yes

2 个答案:

答案 0 :(得分:0)

更新

你可以使用runat = server的隐藏字段并保存是/否。然后将其发送到服务器。

 <input type="hidden" runat="server" value="" id="hidden1" />


function Confirm() {

        if (confirm("Do you want to save data?")) {
            confirm_value.value = "Yes";
            document.getElementById("hidden1").value = "yes";
        } else {
            confirm_value.value = "No";
            document.getElementById("hidden1").value = "no";
        }
        document.forms[0].appendChild(confirm_value);
    }

如果您使用母版页,请记住隐藏的客户端ID与其服务器ID不同。

protected void OnConfirm(object sender, EventArgs e)
{
  string confirmValue = hidden1.Value;       
}

答案 1 :(得分:0)

我认为你想要做的只是当用户确认OK时才执行服务器端按钮?如果是,那么就这样做,基本上当javascript函数返回false时,服务器端按钮不会触发ie :( OnClientClick =&#34; return Confirm()&#34;)

    <script type = "text/javascript">
        function Confirm() {           
            return confirm("Do you want to save data?");
        }
    </script>


    <asp:Button ID="btnConfirm" runat="server" OnClick = "OnConfirm" Text = "Raise Confirm" OnClientClick = "return Confirm()"/>