讓提交按鈕發生驗證事件,其他button按鈕不發生
默認情況下,單擊 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>