禁用的 asp.net 按钮禁用按钮验证

Posted

技术标签:

【中文标题】禁用的 asp.net 按钮禁用按钮验证【英文标题】:Disabled asp.net button disables validation for button 【发布时间】:2011-02-02 23:50:09 【问题描述】:

我有一个包含复选框和按钮的 aspx 页面。在用户选中复选框之前,该按钮默认处于禁用状态。看起来当我将属性 enabled="false" 添加到按钮时,它会删除验证。启用按钮后,我仍然希望验证工作。这是不同部分的代码和标记。

复选框:

<asp:CheckBox runat="server" ID="termsCheckBox" />
<label style="display: inline;">
I agree to the Terms & Conditions</label>

按钮:

<asp:Button runat="server" ID="registerButton" OnClick="registerButton_Click1" 
Text="Register" Enabled="false" ValidationGroup="accountValidation" />

JQuery:

<script type="text/javascript" language="javascript">
$(document).ready(function () 
    $('#<%=termsCheckBox.ClientID %>').click(function () 
        var checked = $(this).val();

        if (checked != undefined)
            $('#<%=registerButton.ClientID %>').removeAttr('disabled');
        else
            $('#<%=registerButton.ClientID %>').attr('disabled', 'disabled');
    );
);
</script>

【问题讨论】:

【参考方案1】:

似乎验证应该附加到复选框,而不是按钮。

【讨论】:

我尝试在复选框上进行验证,但收到一条错误消息,指出 ControlToValidate 对复选框无效。 你使用了什么类型的验证器 - 我在你发布的代码中没有看到它 我正在使用各种,比较,要求,正则表达式 如果你的意思是复选框,我尝试了RequiredValidator就可以了 我很惊讶所需的验证器不起作用 - 尝试使用 javascript 自定义验证器来测试复选框【参考方案2】:

Asp.net 是愚蠢的,因为当一个控件被禁用时,会有各种各样的事情不会发生。

在这种情况下,将不会为禁用的按钮创建导致客户端验证的 js 代码。

如果你尝试从后面的代码中手动添加客户端js代码,

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    registerButton.OnClientClick = String.Format("javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions('0', '', true, '', '', false, false))", registerButton.UniqueID)
End Sub

它不起作用,因为 asp.net 不会呈现禁用控件的所有属性。

那么有两种解决方案。要么在客户端使用 JS 禁用控件,要么添加 javascript 以在客户端执行带有验证的回发。

我为我的程序所做的是添加代码以创建 js 代码以禁用客户端的按钮:

    If btnSubmit.Enabled = False Then
        'Asp.net will not render all the attributes for a control that is disabled.  Even if you
        'try to set the OnClientClick attribute manually in code behind for the control, it will 
        'not work.  Asp.net will not render the attribute.  This is a workaround for this problem.
        btnSubmit.Enabled = True

        strJavaScript &= "btnSubmit.disabled = true;"

    End If

    ClientScript.RegisterStartupScript(Page.GetType(), "myStartupScript", strJavaScript, True)

请注意,btnSubmit 是一个已在我的客户端代码中定义的 javascript 变量。

【讨论】:

【参考方案3】:

我认为如果您在 checkBox 服务器端事件而不是客户端启用/禁用按钮会起作用,因为将生成关联的客户端验证代码以针对按钮的 ValidationGroup 运行

【讨论】:

客户端工作得很好。我不需要为了启用按钮而访问服务器。 我的意思是 asp.net 按钮是 .Net 框架执行的 ValidationGroup 验证的一部分,您需要回发到服务器以确保脚本需要具有按钮附加到客户端上的处理程序。如果您在客户端上有自定义脚本,那么您需要确保它已附加到要触发的按钮的客户端单击事件......除非我错过了什么 好的,我想我理解正确。你是说因为我将它交给客户端而不是回发,所以没有处理按钮的验证,因为它的脚本在启用时没有被添加。 我最终只是在回发期间使用了一些 ajax。

以上是关于禁用的 asp.net 按钮禁用按钮验证的主要内容,如果未能解决你的问题,请参考以下文章

asp.net 使用 Javascript 禁用/启用验证器

ASP.NET 禁用图像按钮

使用 javascript 和 asp.net 启用和禁用按钮

使用 javascript 禁用 asp.net 单选按钮

ASP.NET JQuery,禁用表单提交按钮不调用 httpPost 操作

当页面验证失败时,如何禁用我的 ASP.NET AJAX ConfirmButtonExtender?