RequiredFieldValidator在中继器中不工作
本文关键字:工作 中继器 RequiredFieldValidator | 更新日期: 2023-09-27 18:19:44
我试图将RequiredFieldValidator动态添加到中继器中的RadioButtonList,但失败了,错误为:
Unable to find control id 'rblAccessory_40' referenced by the 'ControlToValidate' property of ''.
本节代码为:
if ((e.Item.ItemType != ListItemType.Header) && (e.Item.ItemType != ListItemType.Footer))
{
Label lblAccID = (Label)e.Item.FindControl("lblAccID");
RadioButtonList rblCondition = (RadioButtonList)e.Item.FindControl("rblCondition");
rblCondition.ID = "rblAccessory_" + lblAccID.Text;
if (conditionList.Count() > 0)
{
RequiredFieldValidator rfv = new RequiredFieldValidator();
rfv.ControlToValidate = "rblAccessory_" + lblAccID.Text;
rfv.ErrorMessage = "Please complete the accessories section";
pnlValidation.Controls.Add(rfv);
rblCondition.DataSource = conditionList;
rblCondition.DataValueField = "id";
rblCondition.DataBind();
}
foreach (ListItem li in rblCondition.Items)
{
li.Text = "";
li.Value = "AccessoryID_" + lblAccID.Text + "-ConditionID_" + li.Value;
}
}
}
它肯定找到了RadioButtonList(rblCondition),因为数据在这一点上绑定正确:
rblCondition.DataSource = conditionList;
rblCondition.DataValueField = "id";
rblCondition.DataBind();
所以我不明白为什么错误显示无法找到控制ID。
我尝试手动指定控制ID,如下所示:
rfv.ControlToValidate = "rblAccessory_" + lblAccID.Text;
也尝试过:
rfv.ControlToValidate = rblCondition.ID;
lblAccID是一个隐藏的文本字段,用于存储中继器中行的ID。
- 将控件指定为在
ItemCreated
事件之后验证属性。我知道这听起来很奇怪,你怎么还会引用动态创建的控件?我通过保留对List<Action>
引用的引用来解决这一问题,我在ItemCreated
期间向该引用添加内容,以便稍后执行
在控制类中,您将声明List<Action>
对象:
List<Action> deferringControlToValidateUntilPreRender = new List<Action>();
在ItemCreated
事件中,您将看到一行类似于:
deferringControlToValidateUntilPreRender.Add(() => rfv.ControlToValidate = rblCondition.UniqueID);
然后,也许在PreRender
:中
foreach(var deferredAction in deferringControlToValidateUntilPreRender) action();
由于RequiredFieldValidator
是客户端代码,因此需要使用控件的客户端id。像这样:
rfv.ControlToValidate = rblCondition.ClientID;
如果你感兴趣,可以从MSDN获得更多信息:
Control.ClientIDMode属性
此外,SO讨论了ClientID和UniqueID之间的差异(如@MushinNoShin的回答中所引用,IMHO的回答是不正确的):
为什么ClientID和UniqueID之间有区别?