Wajeeh Ahmed
Wajeeh Ahmed

Reputation: 13

How to add DataAnnotations attributes to specific properties in a C# class

I wanted to add different DataAnnotations attributes to different instances of My Answer class which is as follows:

 public class AnswerViewModel()
   {
   public String QuestionText {get;set;}
   public String AnswerText {get;set;}
   }

I want to assign different attributes to the QuestionText field in different instances of this class. Like in

AnswerViewModel a1 = new AnswerViewModel();
AnswerViewModel a2 = new AnswerViewModel();

I want the QuestionText field in a1 to have the DateTimeAttribute applied and in a2 the QuestionText field should have the PasswordAttribute applied and so on. I know this will be done via Reflection or the TypeDescriptor but I am completely lost as to how it will be done.

Upvotes: 0

Views: 49

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239290

Not possible. A data annotation will apply to every instance. The only way you could accomplish what you're looking for is to use separate view models:

public abstract class BaseAnswerViewModel
{
    public abstract string QuestionText { get; set; }
    public string AnswerText { get; set; }
}

public class DateTimeAnswerViewModel : BaseAnswerViewModel
{
    [DataType(DataType.DateTime)]
    public override string QuestionText { get; set; }
}

public class PasswordAnswerViewModel : BaseAnswerViewModel
{
    [DataType(DataType.Password)]
    public override string QuestionText { get; set; }
}

Then:

var a1 = new DateTimeAnswerViewModel();
var a2 = new PasswordAnswerViewModel();

Upvotes: 2

Related Questions