【发布时间】:2020-05-30 09:48:14
【问题描述】:
有一些使用数组参数的自定义 MVC 验证器的示例,但仅限于服务器端 - 它们都没有显示使用数组参数实现客户端的示例。
问题是不是在html data-属性中输出数组的内容,而是输出“System.String[]”:
data-val-total-propertynames="System.String[]"
这是我的属性类:
public class TotalAttribute : ValidationAttribute, IClientValidatable
{
private String[] PropertyNames { get; set; }
public TotalAttribute(String[] propertyNames)
{
PropertyNames = propertyNames;
}
protected override ValidationResult IsValid(object value, ValidationContext context)
{
float total = 0;
foreach (var propertyName in PropertyNames)
total += (float)context.ObjectInstance.GetType().GetProperty(propertyName).GetValue(context.ObjectInstance, null);
if (total != (float)value)
return new ValidationResult(FormatErrorMessage(context.DisplayName), new[] { context.MemberName });
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = ErrorMessageString,
ValidationType = "total",
};
rule.ValidationParameters["propertynames"] = PropertyNames;
yield return rule;
}
}
这里是在模型中实现的:
[Total(new string[] { "SomeOtherField1", "SomeOtherField2" }, ErrorMessage = "'Line12Balance' must equal total of 'SomeOtherField1' and 'SomeOtherField2'")]
public decimal? Line12Balance { get; set; }
这里是html data-val 属性输出:
data-val-total-propertynames="System.String[]"
我做错了什么?
【问题讨论】:
标签: arrays asp.net-mvc customvalidator