C#在List< string>上设置数据注释 [英] C# Set Data Annotation on List<string>
本文介绍了C#在List< string>上设置数据注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这段代码:
[Required]
public List<string> myStringList { get; set; }
不幸的是,它不起作用,验证程序完全忽略了它.
Unfortunatelly, it doesn't work, tha validator totally ignores it.
此外,它可以正常工作:
Besides, this works fine:
[Required]
public string myString { get; set; }
和DateTimes也可以正常工作.显然,问题不在于我的验证器,而在于注释.所以问题是,我应该如何在列表上设置数据注释?
and DateTimes work fine as well. Obviously, the problem doesn't lie on my validator, but on the annotation. So the question is, how should I set the Data Annotation on my list ?
推荐答案
创建自己的数据注释属性,例如:
Create your own data annotation attribute, crude example:
public class ListHasElements : ValidationAttribute
{
public override bool IsValid(List mylist)
{
if(mylist == null)
return false;
return mylist.Any();
}
}
然后像这样使用它:
[ListHasElements(ErrorMessage = "List must contain an element")]
public List<string> myStringList { get; set; }
这篇关于C#在List< string>上设置数据注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文