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

时间:2010-03-31 15:18:36

标签: asp.net jquery validation

我有一个包含复选框和按钮的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>

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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变量。

答案 2 :(得分:0)

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

相关问题