Javascript 确认回发 OnClientClick 按钮 ASP.NET

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14058116/
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-08-24 15:36:07  来源:igfitidea点击:

Confirm postback OnClientClick button ASP.NET

javascriptasp.netbuttonpostback

提问by makambi

<asp:Button runat="server" ID="btnUserDelete" Text="Delete" CssClass="GreenLightButton"
                           OnClick="BtnUserDelete_Click"
                           OnClientClick="return UserDeleteConfirmation();" 
 meta:resourcekey="BtnUserDeleteResource1" />

I have tried:

我试过了:

function UserDeleteConfirmation() {
        if (confirm("Are you sure you want to delete this user?"))
            return true;
        else
            return false;
}

and

function UserDeleteConfirmation() {
    if (confirm("Are you sure you want to delete this user?")) {
            __doPostBack(btnUserDelete, '');
    }

    return false;
 }

And none of them works.

它们都不起作用。

回答by Hans Ke?ing

Try this:

尝试这个:

<asp:Button runat="server" ID="btnUserDelete" Text="Delete" CssClass="GreenLightButton"
                       OnClick="BtnUserDelete_Click"
                       OnClientClick="if ( ! UserDeleteConfirmation()) return false;" 
 meta:resourcekey="BtnUserDeleteResource1" />

This way the "return" is only executed when the user clicks "cancel" and not when he clicks "ok".

这样,“返回”仅在用户单击“取消”时执行,而不会在他单击“确定”时执行。

By the way, you can shorten the UserDeleteConfirmation function to:

顺便说一下,您可以将 UserDeleteConfirmation 函数缩短为:

function UserDeleteConfirmation() {
    return confirm("Are you sure you want to delete this user?");
}

回答by chrismay

There are solutions here that will work, but I don't see anyone explaining what is actually happening here, so even though this is 2 years old I'll explain it.

这里有一些可行的解决方案,但我没有看到任何人解释这里实际发生的事情,所以即使这是 2 岁,我也会解释它。

There is nothing "wrong" with the onclientclick javascript you are adding. The problem is that asp.net is adding it's on onclick stuff to run AFTER whatever code you put in there runs.

您添加的 onclientclick javascript 没有任何“错误”。问题是asp.net 正在添加它在onclick 内容上,以便在您放入的任何代码运行后运行。

So for example this ASPX:

例如这个 ASPX:

<asp:Button ID="btnDeny" runat="server" CommandName="Deny" Text="Mark 'Denied'" OnClientClick="return confirm('Are you sure?');" />

is turned into this HTML when rendered:

渲染时变成了这个 HTML:

<input name="rgApplicants$ctl00$ctl02$ctl00$btnDeny" id="rgApplicants_ctl00_ctl02_ctl00_btnDeny" 
onclick="return confirm('Are you sure?');__doPostBack('rgApplicants$ctl00$ctl02$ctl00$btnDeny','')" type="button" value="Mark 'Denied'" abp="547">

If you look closely, the __doPostBack stuff will never be reached, because the "confirm" will always return true/false before __doPostBack is reached.

如果您仔细观察,将永远不会到达 __doPostBack 内容,因为在到达 __doPostBack 之前,“确认”将始终返回 true/false。

This is why you need to have the confirm only return false and not return when the value is true. Technically, it doesn't matter if it returns true or false, any return in this instance would have the effect of preventing the __doPostBack from being called, but for convention I would leave it so that it returns false when false and does nothing for true.

这就是为什么您需要让确认只返回 false 而当值为 true 时不返回。从技术上讲,它是否返回 true 或 false 并不重要,在此实例中的任何返回都会阻止调用 __doPostBack,但为了约定我会保留它以便它在 false 时返回 false 并且不为 true 做任何事情.

回答by Praveen Mitta

You can put the above answers into one line like this. And you don't need to write the function.

您可以像这样将上述答案放在一行中。而且您不需要编写函数。

    <asp:Button runat="server" ID="btnUserDelete" Text="Delete" CssClass="GreenLightButton"
         OnClick="BtnUserDelete_Click" meta:resourcekey="BtnUserDeleteResource1"
OnClientClick="if ( !confirm('Are you sure you want to delete this user?')) return false;"  />

回答by Kapil Khandelwal

Using jQuery UI dialog:

使用 jQuery UI 对话框:

SCRIPT:

脚本:

<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
 $(function () {

            $("#<%=btnUserDelete.ClientID%>").on("click", function (event) {
                event.preventDefault();
                $("#dialog-confirm").dialog({
                    resizable: false,
                    height: 140,
                    modal: true,
                    buttons: {
                        Ok: function () {
                            $(this).dialog("close");
                            __doPostBack($('#<%= btnUserDelete.ClientID %>').attr('name'), '');
                        },
                        Cancel: function () {
                            $(this).dialog("close");
                        }
                    }
                });
            });
 });
</script>

HTML:

HTML:

<div id="dialog-confirm" style="display: none;" title="Confirm Delete">
    <p><span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>Are you sure you want to delete this user?</p>
</div>

回答by RckLN

The code is like this:

代码是这样的:

In Aspx:

在 Aspx 中:

<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" CausesValidation=true />

in Cs:

在 Cs 中:

protected void Page_Load(object sender, System.EventArgs e)
{
     if (!IsPostBack)
     {
         btnSave.Attributes["Onclick"] = "return confirm('Do you really want to save?')";          
     }
}

protected void btnSave_Click(object sender, EventArgs e){
    Page.Validate();
    if (Page.IsValid)
    {
       //Update the database
         lblMessage.Text = "Saved Successfully";
    }
}

回答by Mahmoud Farahat

try this :

尝试这个 :

<asp:Button runat="server" ID="btnUserDelete" Text="Delete" CssClass="GreenLightButton" 
   onClientClick=" return confirm('Are you sure you want to delete this user?')" 
   OnClick="BtnUserDelete_Click"  meta:resourcekey="BtnUserDeleteResource1"  />

回答by Srinivas

try this : OnClientClick="return confirm('Are you sure ?');" Also set : CausesValidation="False"

试试这个: OnClientClick="return confirm('Are you sure ?');" 还设置:CausesValidation="False"

回答by Vinicius

Try this:

尝试这个:

<asp:Button runat="server" ID="btnDelete" Text="Delete"
   onClientClick="javascript:return confirm('Are you sure you want to delete this user?');" OnClick="BtnDelete_Click" />

回答by Jupiter

This is a simple way to do client-side validation BEFORE the confirmation. It makes use of the built in ASP.NET validation javascript.

这是在确认之前进行客户端验证的简单方法。它利用内置的 ASP.NET 验证 javascript。

<script type="text/javascript">
    function validateAndConfirm() {
        Page_ClientValidate("GroupName");  //'GroupName' is the ValidationGroup
        if (Page_IsValid) {
            return confirm("Are you sure?");
        }
        return false;
    }
</script>

<asp:TextBox ID="IntegerTextBox" runat="server" Width="100px" MaxLength="6" />
<asp:RequiredFieldValidator ID="reqIntegerTextBox" runat="server" ErrorMessage="Required"
    ValidationGroup="GroupName"  ControlToValidate="IntegerTextBox" />
<asp:RangeValidator ID="rangeTextBox" runat="server" ErrorMessage="Invalid"
    ValidationGroup="GroupName" Type="Integer" ControlToValidate="IntegerTextBox" />
<asp:Button ID="SubmitButton" runat="server" Text="Submit"  ValidationGroup="GroupName"
    OnClick="SubmitButton_OnClick" OnClientClick="return validateAndConfirm();" />

Source: Client Side Validation using ASP.Net Validator Controls from Javascript

来源:使用来自 Javascript 的 ASP.Net 验证器控件的客户端验证

回答by Anderson Borba

Try this:

尝试这个:

function Confirm() {
    var confirm_value = document.createElement("INPUT");
    confirm_value.type = "hidden";
    confirm_value.name = "confirm_value";

        if (confirm("Your asking")) {
            confirm_value.value = "Yes";
            document.forms[0].appendChild(confirm_value);
        }
    else {
        confirm_value.value = "No";
        document.forms[0].appendChild(confirm_value);
    }
}

In Button call function:

在按钮调用函数中:

<asp:Button ID="btnReprocessar" runat="server" Text="Reprocessar" Height="20px" OnClick="btnReprocessar_Click" OnClientClick="Confirm()"/>

In class .cs call method:

在类 .cs 调用方法中:

        protected void btnReprocessar_Click(object sender, EventArgs e)
    {
        string confirmValue = Request.Form["confirm_value"];
        if (confirmValue == "Yes")
        {

        }
    }