在我的页面上,我有一个使用自定义验证器的文本框:
<asp:CustomValidator ID="cv_Question" ControlToValidate="tb_Question" runat="server" ErrorMessage="*" OnServerValidate="ValidateQuestion" ClientValidationFunction="CheckQuestion" ForeColor="#FF0000" ValidationGroup="CreateUser"></asp:CustomValidator>
我想使用的客户端验证脚本始终为下拉列表 SelectedValue 返回 0,即使下拉列表索引已更改也是如此。
我使用 !Page.IsPostBack 将下拉列表默认索引设置为 0
这是下拉列表:
<asp:DropDownList ID="ddl_Question" runat="server" EnableViewState="true" AutoPostBack="true" onselectedindexchanged="ddl_Question_SelectedIndexChanged">
<asp:ListItem Selected="False" Text="Select a question" Value="0"></asp:ListItem>
<asp:ListItem Selected="False" Text="What was the first movie I ever saw?" Value="1"></asp:ListItem>
<asp:ListItem Selected="False" Text="What is the middle name of my oldest child?" Value="2"></asp:ListItem>
<asp:ListItem Selected="False" Text="In what city was my father born?" Value="3"></asp:ListItem>
<asp:ListItem Selected="False" Text="Who was my favourite cartoon character as a child?" Value="4"></asp:ListItem>
<asp:ListItem Selected="False" Text="What is my mother's middle name?" Value="5"></asp:ListItem>
<asp:ListItem Selected="False" Text="In what year did I meet my significant other?" Value="6"></asp:ListItem>
<asp:ListItem Selected="False" Text="What was my first pet's name?" Value="7"></asp:ListItem>
<asp:ListItem Selected="False" Text="First name of the maid of honour at my wedding?" Value="8"></asp:ListItem>
<asp:ListItem Selected="False" Text="First name of my best friend in elementary school?" Value="9"></asp:ListItem>
<asp:ListItem Selected="False" Text="Name of my all-time favourite movie character?" Value="10"></asp:ListItem>
<asp:ListItem Selected="False" Text="Create a question" Value="11"></asp:ListItem>
</asp:DropDownList>
这是客户端验证:
<script type="text/javascript" language="javascript">
function CheckQuestion(sender, args)
{
var Question = args.Value.toString();
<% if(Convert.ToInt32(ddl_Question.SelectedValue) == 11)
{ %>
if (Question != "" && Question != null)
{
args.IsValid = true;
return;
}
else
{
args.IsValid = false;
return;
}
<% }
else
{ %>
alert(<%= Convert.ToInt32(ddl_Question.SelectedValue)%>);
args.IsValid = true;
return;
<% } %>
}
</script>
如果用户从 ddl_Question 中选择了“创建问题”,我只想验证 tb_Question。
编辑:
这是我的 SelectedIndexChanged 方法。当用户选择“创建问题”时,tb_Question 可见。这发生在任何验证发生之前。
protected void ddl_Question_SelectedIndexChanged(object sender, EventArgs e)
{
if (Convert.ToInt32(ddl_Question.SelectedValue) == 11)
{
Question.Visible = true;
}
else
{
Question.Visible = false;
}
}