我有一个自定义验证属性,我正在从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但是我不能保证属性容器包含我需要的属性(它可以嵌套在其他地方)。
例如,让我们假设我的模型看起来像这样;
public class A
{
[RequiredIf("PropertyB", true)]
public string propertyA { get; set; }
public bool PropertyB { get; set; }
}
有任何想法吗?
在AddValidation方法中使用以下代码:
var viewContext = context.ActionContext as ViewContext viewContext;
var fullName = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(PropertyName);
var fullId = propertyFullName.Replace(".", "_");
注意:TemplateInfo现在在asp.net核心中没有GetFullHtmlFieldId方法