0

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.

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.