默认情况下,单击 Button 控件时会执行页验证。页验证确定页上与验证控件关联的输入控件是否均通过该验证控件所指定的验证规则。
使用 CausesValidation 属性可以指定或确定当单击 Button 控件时是否对客户端和服务器都执行验证。若要禁止执行验证,请将 CausesValidation 属性设置为 false。
对于 reset 或 clear 按钮,此属性通常设置为 false,以防止在单击其中某个按钮时执行验证。
下面的示例演示如何使用 CausesValidation 属性防止发生页面验证。请注意 Validate 方法如何独立地激活每个验证控件.
<%@ Page Language="C#" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
void SubmitButton_Click(Object sender, EventArgs e)
{
// Determine which button was clicked.
switch(((Button)sender).ID)
{
case "CityQueryButton":
// Validate only the controls used for the city query.
CityReqValidator.Validate();
// Take the appropriate action if the controls pass validation.
if (CityReqValidator.IsValid)
{
Message.Text = "You have chosen to run a query for the following city: " +
CityTextBox.Text;
}
break;
case "StateQueryButton":
// Validate only the controls used for the state query.
StateReqValidator.Validate();
// Take the appropriate action if the controls pass validation.
if (StateReqValidator.IsValid)
{
Message.Text = "You have chosen to run a query for the following state: " +
StateTextBox.Text;
}
break;
default:
// If the button clicked isn't recognized, erase the message on the page.
Message.Text = "";
break;
}
}
</script>
</head>
<body>
<form runat="server">
<h3> Button CausesValidation Example </h3>
<table border="1" cellpadding="10">
<tr>
<td>
<b>Enter city to query.</b> <br>
<asp:TextBox ID="CityTextBox"
runat="server"/>
<asp:RequiredFieldValidator ID="CityReqValidator"
ControlToValidate="CityTextBox"
ErrorMessage="<br>Please enter a city."
Display="Dynamic"
EnableClientScript="False"
runat="server"/>
</td>
<td valign="bottom">
<asp:Button ID="CityQueryButton"
Text="Submit"
CausesValidation="False"
OnClick="SubmitButton_Click"
runat="server"/>
</td>
</tr>
<tr>
<td>
<b>Enter state to query.</b> <br>
<asp:TextBox ID="StateTextBox"
runat="server"/>
<asp:RequiredFieldValidator ID="StateReqValidator"
ControlToValidate="StateTextBox"
ErrorMessage="<br>Please enter a state."
Display="Dynamic"
EnableClientScript="False"
runat="server"/>
</td>
<td valign="bottom">
<asp:Button ID="StateQueryButton"
Text="Submit"
CausesValidation="False"
OnClick="SubmitButton_Click"
runat="server"/>
</td>
</tr>
</table>
<br><br>
<asp:Label ID="Message"
runat="Server"/>
</form>
</body>
</html>