ASP.Net 按钮控件上的 JavaScript 确认
我正在开发一个 ASP.Net C# 应用程序,我想创建一个按钮控件,当用户单击按钮时,会弹出一个 JavaScript 确认窗口,然后从用户那里获取布尔值(是/否)以在按钮中执行进一步的操作onClick 事件。
我当前的方法是在按钮中添加 OnClientClick 和 OnClick 事件,其中 OnClientClick 触发 JavaScript 函数并将(是/否)值存储到 HiddenField Control 中以在 OnClick 事件期间使用。
它类似于以下代码片段:
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" />
有没有更好的方法来做到这一点?提前谢谢您。
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.
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更改您的 CreatePopup() 函数以返回布尔值:
然后确保从按钮中的
OnClientClick()
返回该值:使用该方法,仅当
OnClientClick()
方法返回 true 时才会触发OnClick()
方法。Change your CreatePopup() function to return a boolean:
And then ensure you return that from the
OnClientClick()
in the button:<asp:Button ... OnClientClick="return CreatePopup();" />
Using that method, the
OnClick()
method will only fire if theOnClientClick()
method returns true.为什么要将 JavaScript 确认的值存储在隐藏字段中?当确认值为 'no' 时,只需在 JavaScript 函数中返回 false 即可阻止表单提交。当 cnfirm 值为 yes 时,返回 true 以允许提交表单。在 Button_click 方法后面的代码中,您不必检查 JavaScript 确认中发生的情况,因为如果用户拒绝,则永远不会提交表单。
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.