C# 从ClientModelValidationContext访问完整的html字段属性

C# 从ClientModelValidationContext访问完整的html字段属性,c#,validation,asp.net-core,C#,Validation,Asp.net Core,我有一个自定义验证属性,正在从asp.net迁移到asn.net-core。这是一个实现IClientModelValidator的简单requiredif属性 public class RequiredIfAttribute : ValidationAttribute, IClientModelValidator { private String PropertyName { get; set; } private Object DesiredValue

我有一个自定义验证属性,正在从asp.net迁移到asn.net-core。这是一个实现IClientModelValidator的简单requiredif属性

public class RequiredIfAttribute : ValidationAttribute, IClientModelValidator
    {
        private String PropertyName { get; set; }
        private Object DesiredValue { get; set; }

        private readonly RequiredAttribute _innerAttribute;

        public RequiredIfAttribute(String propertyName, Object desiredvalue)
        {
            PropertyName = propertyName;
            DesiredValue = desiredvalue;
            _innerAttribute = new RequiredAttribute();
        }

        protected override ValidationResult IsValid(object value, ValidationContext context)
        {
            var dependentValue = context.ObjectInstance.GetType().GetProperty(PropertyName).GetValue(context.ObjectInstance, null);

            if (dependentValue.ToString() == DesiredValue.ToString())
            {
                if (!_innerAttribute.IsValid(value))
                {
                    return new ValidationResult(FormatErrorMessage(context.DisplayName), new[] { context.MemberName });
                }
            }
            return ValidationResult.Success;
        }

        public void AddValidation(ClientModelValidationContext context)
        {
            context.Attributes.Add("data-val", "true");
            context.Attributes.Add("data-val-requiredif", ErrorMessage);

            //this following line is the issue
            context.Attributes.Add("data-val-requiredif-dependentproperty", (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(PropertyName));
            context.Attributes.Add("data-val-requiredif-desiredvalue", DesiredValue.ToString());

        }
    }
正如我在AddValidation方法中的上述行中所评论的那样,通过将上下文转换为ViewContext并以这种方式访问它的名称,我似乎无法像在asp.net中那样获得完整的html字段id

获取非当前上下文属性的完整html字段id的新方法是什么

例如旧代码

(context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(PropertyName)
可能返回了一个路径,如“viewModel.ComplexObject.PropertyID”

我已经尝试在上下文的ModelMetaData.ContainerContext中查找,但我不能保证properties容器包含我需要的属性(它可能嵌套在该容器的其他位置)

例如,假设我的模型看起来是这样的

 public class A
    {
        [RequiredIf("PropertyB", true)]
        public string propertyA { get; set; }

        public bool PropertyB { get; set; }
    }

有什么想法吗?

在添加验证方法中使用以下代码:

var viewContext = context.ActionContext as ViewContext viewContext;

var fullName = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(PropertyName);

var fullId = propertyFullName.Replace(".", "_");

注意:TemplateInfo现在在asp.net core

集合中没有GetFullHtmlFieldDid方法,还需要:
。替换(“[”,“”)。替换(“]”,“”)