gpt4 book ai didi

asp.net - asp:CustomValidator/OnServerValidate

转载 作者:行者123 更新时间:2023-12-03 23:16:56 24 4
gpt4 key购买 nike

我有一个CheckBoxList,我正在尝试验证是否至少选中了一个复选框。

标记:

<asp:CustomValidator ID="RequiredFieldValidator8" ValidationGroup="EditArticle"
runat="server" ErrorMessage="At least one Category is required."
OnServerValidate="topic_ServerValidate" />
<asp:CheckBoxList id="checkboxlistCategories" runat="server"></asp:CheckBoxList>


后台代码:

protected void topic_ServerValidate(object source, ServerValidateEventArgs args)
{
int i = 0;
foreach (ListItem item in checkboxlistCategories.Items)
{
if (item.Selected == true)
i = i + 1;
}
if (i == 0)
args.IsValid = false;
else
args.IsValid = true;
}


如果我在CustomValidator控件中添加ControlToValidate =“ checkboxlistCategories”,它会爆炸!我得到的异常是:


System.Web.HttpException:控制“ checkboxlistCategories”,由“ RequiredFieldValidator8”的ControlToValidate属性引用


我想念什么吗?

最佳答案

这是一个更干净的jQuery实现,它允许一个ClientValidationFunction用于页面上任意数量的CheckBoxList控件:

function ValidateCheckBoxList(sender, args) {
args.IsValid = false;

$("#" + sender.id).parent().find("table[id$="+sender.ControlId+"]").find(":checkbox").each(function () {
if ($(this).attr("checked")) {
args.IsValid = true;
return;
}
});
}


这是标记:

<asp:CheckBoxList runat="server"
Id="cblOptions"
DataTextField="Text"
DataValueField="Id" />

<xx:CustomValidator Display="Dynamic"
runat="server"
ID="cblOptionsValidator"
ControlId="cblOptions"
ClientValidationFunction="ValidateCheckBoxList"
ErrorMessage="One selection required." />


最后,定制验证器允许客户端功能按ID检索目标控件:

public class CustomValidator : System.Web.UI.WebControls.CustomValidator
{
public string ControlId { get; set; }

protected override void OnLoad(EventArgs e)
{
if (Enabled)
Page.ClientScript.RegisterExpandoAttribute(ClientID, "ControlId", ControlId);

base.OnLoad(e);
}
}

关于asp.net - asp:CustomValidator/OnServerValidate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2500637/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com