下拉列表中的RequiredFieldValidator 不接受空对象的IntialValue
我已通读此内容,这帮助我缩小了验证范围RequiredFieldValidator
的 InitialValue
属性存在问题。
我的下拉列表是一个对象列表,这些对象由后面的代码填充,如下所示;
brands.Insert(0, Brand.Empty)
cbBrand.DataValueField = "ID";
cbBrand.DataTextField = "Name";
cbBrand.DataSource = new BindingList<Brand>(brands);
cbBrand.DataBind();
其中 Brand.Empty 是空对象类型。
我遇到困难的地方是让 IntialValue
接受空值。例如,InitialValue=""
无法识别列表中的空对象。
谁能指出我解决这个问题的方向吗?
I have read through this which helped me narrow down my validation problems to the InitialValue
property of the RequiredFieldValidator
.
My drop down list is a list of objects which are populated by the code behind like this;
brands.Insert(0, Brand.Empty)
cbBrand.DataValueField = "ID";
cbBrand.DataTextField = "Name";
cbBrand.DataSource = new BindingList<Brand>(brands);
cbBrand.DataBind();
where Brand.Empty is a null object type.
Where I'm coming unstuck is getting the IntialValue
to accept a null value. For instance, InitialValue=""
fails to recognise the empty object in the list.
Can anyone point me in the direction of a fix for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
空字符串与空值不同。不要向数据源添加空值,而是直接将其添加到下拉列表中,如下所示:
这将向 HTML 选择元素添加一个值为“”的选项,该选项与验证器初始值匹配。
An empty string is not the same as a null value. Instead of adding a null value to your data source, add it to the drop down directly like :
That will add a option to your HTML select element with a value of "", which matches the validators initial value.
哇。我以为在发布这个问题之前我已经非常彻底地搜索了该网站上以前的答案,但我错过了 这个!
答案是将您的
更改为具有属性AppendDataBoundItems=true
,然后添加一个
在 dropDownList 标记和 BAM! 之间您可以向列表中插入一个值,该值不需要在后面的代码中插入空对象(应该将其删除,这样您就不会在列表开头出现 2 个空格)。这里的好处是我的代码隐藏中的列表绑定到对象类型
,但在客户端添加空字符串对于客户端验证来说效果很好。希望这可以帮助其他遇到这个问题的人!
Wow. I thought I had searched previous answers on this site very thoroughly before posting this question, but I had missed this!!
The answer is to change your
<asp:DropDownList>
to have the propertyAppendDataBoundItems=true
, Then add an<asp:ListItem Text="" Value="" />
between the dropDownList tags and BAM! you can insert a value to the list that does not require the null object inserted in the code behind (which should be removed so that you don't end up with 2 blanks at the start of your list).The benefit here is that the list in my code-behind is bound to an object type
<Brand>
, but adding the empty string at the client works fine for client-side validation.Hope this helps anyone else struggling with this problem!