C# Set Data Annotation on List<string> [duplicate]

那年仲夏 提交于 2021-02-16 13:34:01

问题


I have this piece of code:

[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; }

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 ?


回答1:


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();   
   }
}

Then use it like:

[ListHasElements(ErrorMessage = "List must contain an element")]
public List<string> myStringList { get; set; }



回答2:


On top of what @DGibbs has specified if you want to perform client side validation you need to inherit IClientValidatable interface in custom class attribute and overriding GetClientValidationRules method. This will register client script like JavaScript function and the parameters within those methods. Please see this example and this



来源:https://stackoverflow.com/questions/17449651/c-sharp-set-data-annotation-on-liststring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!