ASP.Net 按钮控件上的 JavaScript 确认

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7886451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:38:50  来源:igfitidea点击:

JavaScript Confirm on ASP.Net Button Control

c#javascriptasp.netpopup

提问by sams5817

I working on an ASP.Net C# application, I wanted to create a Button Control, when user click on the button, a JavaScript confirm popup, then get the Boolean value from the user (Yes/No) to perform further actions in the button onClick event.

我在 ASP.Net C# 应用程序上工作,我想创建一个按钮控件,当用户单击按钮时,JavaScript 确认弹出窗口,然后从用户那里获取布尔值(是/否)以在按钮中执行进一步的操作onClick 事件。

my current approach was added OnClientClick and OnClick event in the button, where OnClientClick trigger JavaScript function and the (Yes/No) value is store into HiddenField Control to make use during OnClick event.

我目前的方法是在按钮中添加 OnClientClick 和 OnClick 事件,其中 OnClientClick 触发 JavaScript 函数,并将(是/否)值存储到 HiddenField 控件中以在 OnClick 事件期间使用。

It is something like the following code fragments:

它类似于以下代码片段:

function CreatePopup(){
            var value = confirm("Do you confirm?");
            var hdn1 = document.getElementById('hdn1');
            hdn1.Value = value;
        }

<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" OnClientClick="CreatePopup()"/>
<asp:HiddenField ID="hdn1" runat="server" />

Is there any better approach in order to do this? thank you in advanced.

有没有更好的方法来做到这一点?提前谢谢你。

回答by Sir Crispalot

Change your CreatePopup() function to return a boolean:

更改您的 CreatePopup() 函数以返回一个布尔值:

function CreatePopup()
{
    return confirm("Do you confirm?");
}

And then ensure you return that from the OnClientClick()in the button:

然后确保您从OnClientClick()按钮中返回:

<asp:Button ... OnClientClick="return CreatePopup();" />

<asp:Button ... OnClientClick="return CreatePopup();" />

Using that method, the OnClick()method will only fire if the OnClientClick()method returns true.

使用该方法,该OnClick()方法只会在该OnClientClick()方法返回 true 时触发。

回答by newbie

Why do you want to store the value of the JavaScript confirmation in the hidden field? Just simply return false in your JavaScript function when the confirm value is 'no' , to prevent the form from submitting. When cnfirm value is yes, return true to allow the form to be submitted. In your code behind in the button_click method you don't have to check what happened in your JavaScript confirm, since form will never be submitted if the user said no.

为什么要将 JavaScript 确认的值存储在隐藏字段中?当确认值为 'no' 时,只需在 JavaScript 函数中返回 false 即可,以防止表单提交。当cnfirm值为yes时,返回true允许表单提交。在 button_click 方法后面的代码中,您不必检查 JavaScript 确认中发生的事情,因为如果用户拒绝,表单将永远不会提交。