2010-03-31 129 views
2

我有一个aspx页面,其中包含一个复选框和一个按钮。该按钮在默认情况下被禁用,直到用户选中该复选框。它看起来像当我添加属性enabled =“false”到按钮时,它将删除验证。当按钮启用时,我仍然希望验证工作。这里是不同部分的代码和标记。已禁用的asp.net按钮禁用按钮验证

复选框:

<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> 

回答

0

我认为,如果你启用了它的工作/禁用的复选框服务器端事件的按钮,而不是客户端,因为相关的客户端验证代码将生成的ValidationGroup按钮

+0

客户端工作得很好。我不需要去服务器去启用一个按钮。 – Xaisoft 2010-03-31 15:29:32

+0

我的意思是,将asp.net按钮作为.Net框架执行的验证组验证的一部分,您需要回发到服务器以确保脚本需要将按钮附加到客户端上的处理程序。如果你在客户端有自定义脚本,那么你需要确保它已经连接到客户端点击事件的按钮被解雇......除非我错过了一些东西 – Sunny 2010-03-31 15:36:21

+0

好吧,我想我正确地得到了你。您是否在说因为我在客户端处理它,而没有回发,因此按钮的验证没有被处理,因为它的脚本在启用时未被添加。 – Xaisoft 2010-03-31 15:46:00

2

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

+0

我试图在复选框上进行验证,并且我收到了一条错误消息 ,表示ControlToValidate对于复选框无效。 – Xaisoft 2010-03-31 15:28:51

+0

你使用的是什么类型的验证程序 - 我在你发布的代码中没有看到它 – Ray 2010-03-31 15:33:37

+0

我正在使用各种,比较,要求,RegularExpression – Xaisoft 2010-03-31 15:34:28

2

天冬氨酸的运行.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变量。