그래서 아래 모델을 가지고 있으며 내 데이터의 유효성을 검사하기 위해 맞춤 데이터 주석을 만들려고합니다. 그것은 RequiredIf()입니다. 첫 번째 인수는 속성 이름이고 두 번째 인수는 해당 속성 이름과 동일해야합니다.두 개의보기 모델에서 맞춤식 주석을 확인하려면 어떻게해야합니까?
내가하려는 것은 QuestionViewModel QuestionType을보고 "text"인지 확인한 다음이 필드가 필요한지 확인하는 것입니다. 하지만 QuestionViewViewModel 안에 있는데 QuestionViewModel에 액세스 할 수있는 주석을 만드는 방법이 확실하지 않습니다.
그럼 아래 로직을 잘 살펴보면 QuestionViewModel에서 잘 작동합니다. 하지만 QuestionOptionViewModel 안에있을 때가 아닙니다. 내 requiredIf 클래스에서 다른 viewmodel의 속성에 액세스하려면 어떻게해야합니까?
모델 :
public class QuestionViewModel
{
public int? Id { get; set; }
public string QuestionType { get; set; }
public string SubType { get; set; }
public string Text { get; set; }
public int SortOrder { get; set; }
public bool IsHidden { get; set; }
[RequiredIf("QuestionType", "radio", ErrorMessage = "Radio Reqired")]
public int? Selected { get; set; }
public List<QuestionOptionViewModel> Options { get; set; }
}
public class QuestionOptionViewModel
{
public int? Id { get; set; }
public string Text { get; set; }
[RequiredIf("QuestionType", "text", ErrorMessage = "Required Field")]
public string Value { get; set; }
public bool IsChecked { get; set; }
}
사용자 정의 데이터 주석 :
public class RequiredIfAttribute : RequiredAttribute
{
private String PropertyName { get; set; }
private Object DesiredValue { get; set; }
public RequiredIfAttribute(String propertyName, Object desiredValue)
{
PropertyName = propertyName;
DesiredValue = desiredValue;
}
protected override ValidationResult IsValid(object value, ValidationContext context)
{
Object instance = context.ObjectInstance;
Type type = instance.GetType();
Object propertyValue = type.GetProperty(PropertyName).GetValue(instance, null);
if (propertyValue.ToString() == DesiredValue.ToString())
{
ValidationResult result = base.IsValid(value, context);
return result;
}
return ValidationResult.Success;
}
}