开发者

How i can use two optional object in c# when one of them is required?

开发者 https://www.devze.com 2023-04-01 06:11 出处:网络
i got the information on page through query-string and i validate them through the data annotation feature.

i got the information on page through query-string and i validate them through the data annotation feature.

on the page i got the pId or eId. the one of them in every situation the one of them are always found how i can validate them in MVC.

can someone tell me how i can do this in c# asp.net mvc through the data-annotation.

are this works if i do it

 public string pId 
        {
            get;
            set
            {
                eId= value;
                pId = value;
            }
       开发者_运维知识库 }

        public string eId
        {
            get;
            set;
        }


If I understand you correctly the situation is that you allways need either pId set OR eId - one of them might be null/empty but never both. And you want to do this with some kind of DataAnotation instead of some other kind of validation.

I don't know if this is possible directly with what is there but I doubt. But you can implement your own custom validation attribute (as Phil shows how in this great blog-post):

I guess to work this with this you need to extract your EId/PId into a Id-class because the object to validate will be value of your annotated field.

Another way would be to implement the IValidatableObject-Interface (see this blog post)

Here is a example for your type

class MyClass : IValidatableObject
{
   public string EId {get;set;}
   public string PId {get;set;}

   public IEnumerable<ValidationResult> Validate(ValidationContext vC)
   {
      if (string.IsNullOrEmpty(EId) && string.IsNullOrEmpty(PId))
         yield return new ValidationResult("one of EId or PId must be set!", new []{ "EId", "PId" });
   }

}

And finaly here is a nice overview on MSDN:

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号